• Now all data be ready for publish, We had made our blog alive now. Haha.



  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…



Flask to return image stored in database- Stack Overflow

Python PingBook 1 months ago (10-23) 19 0

Question

My images are stored in a MongoDB, and I’d like to return them to the client, here is how the code is like:

@app.route(“/images/.jpg”)
def getImage(pid):
# get image binary from MongoDB, which is bson.Binary type
return image_binary

However, it seems that I can’t return binary directly in Flask? My idea so far:

Return the base64 of the image binary. The problem is that IE<8 doesn't support this. Create a temporary file then return it with send_file. Are there better solutions?

Answer

Create a response object with the data and then set the content type header. Set the content disposition header to attachment if you want the browser to save the file instead of displaying it.

@app.route(‘/images/.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

Relevant: werkzeug.Headers and flask.Response

You can pass a file-like oject to and the header arguments to send_file to let it set up the complete response. Use io.BytesIO for binary data:

return send_file(
io.BytesIO(image_binary),
mimetype=’image/jpeg’,
as_attachment=True,
attachment_filename=’%s.jpg’ % pid)




Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
For reprinting, please indicate the link of the original text:Flask to return image stored in database- Stack Overflow
LIKE (0)
[1725641479@qq.com]
SHARE (0)
PingBook
Author:
We create, We sharing! Tag every value data your sharing
Submit comments
Cancel comments
emoji picture bold strikethrough center italic check in

Hi,you need to provide your name and email adress!

  • Name (Required)
  • Email (Required)
  • Website