158

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

264

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.

Sign up to request clarification or add additional context in comments.

6 Comments

any idea how to do that with flask-restful ?
@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.
how do i send multiple gifs as return here?
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
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' ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.