I am trying to read a set of records from db which has a blob field. I am able to read it but not without saving it to disk first.
cursor.execute(\"select im
I am planning to use render_template to display the data
To serve the images from a blob field, you need to create a separate route which serves the actual image data specifically, then in a template include links which load the files from this route.
There's no need to use PIL here, as the blob field gives you bytes data. You run that through BytesIO to get a _io.BytesIO
object, which can be passed straight to Flask's send_file
function.
from io import BytesIO
from flask import send_file
@app.route('/image/<int:ident>')
def image_route(ident):
# This can only serve one image at a time, so match by id
cursor.execute("select image from dept_master WHERE id = ?", (ident,)
result = cursor.fetchone()
image_bytes = result[0]
bytes_io = BytesIO(image_bytes)
return send_file(bytes_io, mimetype='image/jpeg')
At this stage you should be able to hit /image/1
and see the image in your browser for the row with id 1
.
Then, somewhere in a template, just include the link for this with:
<img src='{{ url_for("image_route", ident=image_ident) }}' />
This assumes that image_ident
is available in the template. You might need to replace this variable name with something which exsists (could be a variable within a for loop which denotes the image id to pull).
Let me know if this needs further explaining.