2015-07-11 99 views
4

我有一个存储为二进制blob图像的模型。我想在模板中显示此图像以及有关该对象的其他数据。由于图像不是一个单独的文件,我无法弄清楚如何显示它。我尝试设置标题,或使用send_filerender_template,但我要么没有得到图像或只有获得图像,而不是模板的其余部分。如何在模板中将二进制blob显示为图像?在模板中以二进制blob存储的显示图像

class A(ndb.Model): 
    id= ndb.IntegerProperty() 
    x= ndb.StringProperty() 
    y= ndb.StringProperty() 
    image = ndb.BlobProperty() 

回答

7

图像以字节形式存储。使用base64对其进行编码,并将其作为数据URI插入到呈现的HTML中。您可以将对象及其编码图像传递给模板。

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) 
    return render_template('show_a.html', obj=obj, image=image) 
<p>{{ obj.x }}<br/> 
{{ obj.y }}</p> 
<img src="data:;base64,{{ image }}"/> 

这是次优的,因为数据URI发送每次呈现页面时,在显示图像文件可以由客户端缓存。将图像文件存储在目录中,将路径存储在数据库中,然后单独提供图像文件会更好。