147

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?

0

1 Answer 1

242

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.

6
  • 2
    any idea how to do that with flask-restful ?
    – David V.
    Aug 23, 2017 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. Sep 26, 2017 at 20:05
  • how do i send multiple gifs as return here?
    – Dhanapal
    Dec 5, 2017 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
    – Vaulstein
    Apr 5, 2018 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' ? Jun 4, 2020 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.