How to return images in flask response?

PythonFlask

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionwong2View Question on Stackoverflow
Solution 1 - PythonMartin GeislerView Answer on Stackoverflow