从数据库读取Blob而不保存到Python中的磁盘 [英] Reading blob from database without saving to disk in Python
问题描述
我正在尝试从具有blob字段的db读取一组记录.我能够读取它,但不能不先将其保存到磁盘.
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 ?
推荐答案
我打算使用render_template来显示数据
I am planning to use render_template to display the data
要从Blob字段中提供图像,您需要创建一条单独的路径来专门提供实际的图像数据,然后在模板中包含从该路径加载文件的链接.
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.
这里不需要使用PIL,因为blob字段为您提供了字节数据.您可以通过BytesIO运行该对象,以获得一个_io.BytesIO
对象,该对象可以直接传递给Flask的send_file
函数.
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')
在这个阶段,您应该可以点击/image/1
并在浏览器中看到ID为1
的行的图像.
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) }}' />
这假定image_ident
在模板中可用.您可能需要将此变量名替换为现有的变量名(可能是for循环中的变量,表示要提取的图像ID).
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.
这篇关于从数据库读取Blob而不保存到Python中的磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!