151

As an example, this URL:

http://example.com/get_image?type=1

should return a response with a image/gif MIME type. I have two static .gif images,
and if type is 1, it should return ok.gif, else return error.gif. How to do that in flask?

Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
wong2
  • 34,358
  • 48
  • 134
  • 179

1 Answers1

247

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
  • 2
    any idea how to do that with flask-restful ? – David V. Aug 23 '17 at 15:32
  • 1
    @DavidV. I am trying the same thing. I am going to use an alternate for now. Save the response as a png file and somehow create a URL for that . Then embed that URL in my html page. – Arindam Roychowdhury Sep 26 '17 at 20:05
  • how do i send multiple gifs as return here? – Dhanapal Dec 05 '17 at 12:14
  • 12
    It is worth nothing that `send_file` is an insecure method of sending files, which does not do any sanity checks and is not recommended if sanity checks are handled in your code. More information can be found on this [answer](https://stackoverflow.com/questions/38252955/flask-when-to-use-send-file-send-from-directory) – Vaulstein Apr 05 '18 at 14:28
  • what is the path of an image should i write? should i specify the path from the root directory: ```filename = './flaskapp/assets/imgs/ok.gif'``` ? – Alexey Nikonov Jun 04 '20 at 15:32
  • @AlexNikonov just pass the endpoint that calls returns the actual path of the file. So, for `@app.route('/vid/')` which returns `send_file('path_of_video')`, pass ` – jsdbt Sep 12 '20 at 02:26