Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

flask - Reading blob from database without saving to disk in Python

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 image ,id, 
department from dept_master")
depdata = cursor.fetchall()
for row in depdata:
    file_like = io.BytesIO(row[0])
    file = PIL.Image.open(file_like)
    target = os.path.join("/path-to-save/", 'folder-save')
    destination = "/".join([target, file.filename])
    file.save(destination) 

How can I read it and display it without first saving to disk ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...