使用Flask/Python以HTML格式呈现sqlite服务器中的Blob

2024-10-01 04:59:05 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码使用MyDB中的值呈现html模板

        displayrows = db.execute("SELECT * FROM profiles WHERE profile_id = :profile_id", (session["user_id"],))
        displayrows = db.fetchall()
        displaycount = db.execute("SELECT COUNT(*) FROM bucketlist WHERE wish_id = :wish_id", (session["user_id"],))
        for i in displayrows:
            bytes_io = BytesIO(i[5])
        for i in displaycount:
            return render_template("profile.html", rows = displayrows, count = i[0], image = bytes_io)

这是呈现值的html页面的一部分

<div class="card bg-dark" style="width: 18rem;">
    <p class="list-group-item">BucketList Size - {{ count }}</p>
    {%for row in rows%}
        <ul class="list-group list-group-flush">  
            <li class="list-group-item">Location - {{ row[1] }}, {{row[2]}}</li>
            <li class="list-group-item">Looking for - {{row[3] }}</li>
            <li class="list-group-item">Bio - {{row[4]}}</li>
        </ul>  
    {%endfor%}
         <img src="{{image}}" />
</div>

一般来说,我对python、flask和编码非常陌生,因此如果有人愿意花时间解释我如何在html页面上成功显示blob列中的数据,我将不胜感激。提前谢谢


Tags: inidforexecutedbhtmlgroupli
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:05

以下是几点观察:

  • 在for循环中不能有return语句。view函数只能返回一次
  • 您需要一条路径来呈现配置文件页面,另一条路径来返回图像

我想我是在假设你在这里要做什么,但希望这是有意义的


具有一个呈现配置文件页面的路由:

@app.route('/profile')
def profile():

    # You could pull several profiles here, but as you provide an id it just pulls one:
    db.execute("SELECT * FROM profiles WHERE profile_id = ?", (session["user_id"],))

    # Again, this supports multiple had the query been `SELECT * FROM profiles`
    displayrows = db.fetchall()
    
    return render_template("profile.html", rows = displayrows)

然后在模板profile.html中,在for循环中使用flask的url_for函数生成指向图像的链接,将row[0](应该是该配置文件的id)作为ident参数传递:

{% for row in rows %}
        ...
        <img src='{{ url_for("profile_image", ident = row[0]) }}' />
        ...
{% endfor %}

url_for函数将为下一个路由输出正确的超链接。请注意,这是如何接受作为概要文件id的ident。您需要将your_blob_col替换为包含bolb的列标题:

from flask import send_file

@app.route('/i/<int:ident>')
def profile_image(ident):
    db.execute("SELECT your_blob_col FROM profiles WHERE profile_id = ?", (ident,))
    result = db.fetchone() # There's only one
    image_bytes = result[0] # The first and only column

    bytes_io = BytesIO(image_bytes)

    return send_file(bytes_io, mimetype='image/jpeg')  

因此<img>标记中的超链接将呈现为类似/i/123的内容,当由profile_image函数处理时,它将返回图像数据

您可以在浏览器的开发工具(网络选项卡)中检查这些请求,以便更好地了解正在发生的事情。如果您的profile函数取而代之的是拉取n配置文件,那么您将看到对profile路由的1个请求,以及对profile_image路由的n请求

如果有任何不清楚的地方,请告诉我:)

相关问题 更多 >