2

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  
Community
  • 1
  • 1
bernie2436
  • 22,841
  • 49
  • 151
  • 244

1 Answers1

5

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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343