python提取blob数据 乱码_从数据库读取Blob而不保存到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 ?

解决方案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/')

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:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值