且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从数据库读取Blob而不保存到Python中的磁盘

更新时间:2021-08-03 22:08:54

我打算使用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.