Categories
Python Answers

How to return image stored in database with Python Flask?

Spread the love

Sometimes, we want to return image stored in database with Python Flask.

In this article, we’ll look at how to return image stored in database with Python Flask.

How to return image stored in database with Python Flask?

To return image stored in database with Python Flask, we can use the make_response function.

For instance, we write

@app.route('/images/<int:pid>.jpg')
def get_image(pid):
    image_binary = read_image(pid)
    response = make_response(image_binary)
    response.headers.set('Content-Type', 'image/jpeg')
    response.headers.set(
        'Content-Disposition', 'attachment', filename='%s.jpg' % pid)
    return response

to call make_response on the image_binary image.

Then we call response.headers.set to add a new response headers for the file.

And then we return the response with the image as the body and the headers.

Conclusion

To return image stored in database with Python Flask, we can use the make_response function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *