Display image stored as binary blob in template

后端 未结 1 504
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 13:10

I have a model with an image stored as a binary blob. I want to display this image, along with other data about the object, in a template. Since the image is not a separat

相关标签:
1条回答
  • 2020-12-01 13:34

    The image is stored as bytes. Encode it with base64 and insert it as a data URI in the rendered HTML. You can pass both the object and its encoded image to the template.

    from base64 import b64encode
    
    @app.route("/show/<int:id>")
    def show(id):
        obj = A.query(A.id == id).fetch(1)[0]
        image = b64encode(obj.image).decode("utf-8")
        return render_template("show_a.html", obj=obj, image=image)
    
    <p>{{ obj.x }}<br/>
    {{ obj.y }}</p>
    <img src="data:;base64,{{ image }}"/>
    

    This is sub-optimal, because data URIs are sent every time the page is rendered, while an image file can be cached by the client. It would be better to store the image file in a directory, store the path in the database, and just serve the image file separately.

    0 讨论(0)
提交回复
热议问题