bernie2436
bernie2436

Reputation: 23901

Why can't flask find this file?

I am trying to return a jpg file from a get request in Flask using this answer as a guide How to return images in flask response?

I have this code running in my root directory (off a tornado server):

@app.route('/pic/<string:address>', methods= ["GET"])
def here(address=None):
    return send_file(url_for('static', filename='images/123_Octavia_St.jpg'), mimetype='image/jpg')

I have the file located at rootdirectory/static/images/123_Octavia_St.jpg

I am getting this error:

IOError: [Errno 2] No such file or directory: '/static/images/123_Octavia_St.jpg'

Here are the paths:

$ pwd
pathto/rootdirectory/static/images
$ ls
123_Octavia_St.jpg  

Upvotes: 2

Views: 3490

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

Don't use url_for(); that's for generating URLs, not file paths.

Instead, use send_from_directory() with the static directory as the root:

from flask import app, send_directory

@app.route('/pic/<string:address>', methods= ["GET"])
def here(address=None):
    return send_from_directory(app.static_folder, 'images/123_Octavia_St.jpg', mimetype='image/jpg')

or, for static files, just reuse the view Flask uses for serving static files itself, app.send_static_file():

from flask import app

@app.route('/pic/<string:address>', methods= ["GET"])
def here(address=None):
    return app.send_static_file('images/123_Octavia_St.jpg')

Upvotes: 5

Related Questions