2014-09-30 81 views
4

你好,我使用烧瓶,Jinja2的,SQLAlchemy的使用Python开发小的应用程序,... 我节省在我的数据库binare数据:编码瓶/ Jinja2的二进制数据

file = request.files['file'] 
# store the recipe 
recipe = Recipe(None, session['user_in'], request.form['title'], request.form['text'],request.form['tags'], file.read()) 
db.session.commit() 

,我想展现在我的应用程序的条目:

@app.route('/recipe/<id>', methods=['GET', 'POST']) 
def show_entry(id): 
    return render_template('show_entry.html', entry=db_session.query(Recipe).get(id)) 

而且在我的模板,我有:

<img src="data:image/png;base64,{{ entry.image }}"/> 

但我有unicode错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128) 

你能帮我解决这个问题吗?

回答

4

data:image/png;base64,说PNG数据是base64编码,所以我认为你需要在渲染模板之前base64编码图像数据。如果你这样做,编码错误应该消失。这样的事情应该做的伎俩:

@app.route('/recipe/<id>', methods=['GET', 'POST']) 
def show_entry(id): 
    entry = db_session.query(Recipe).get(id) 
    entry.image = entry.image.encode('base64') 
    return render_template('show_entry.html', entry=entry) 

我不是太熟悉,它可能是一个字典查找?,即

entry['image'] = entry['image'].encode('base64') 
+0

感谢我使用base64.encode和它的作品 – Cospel 2014-09-30 11:28:19

+0

@ Cospel - 没问题。哪一个是正确的语法 - 属性引用或字典查找? – mhawke 2014-09-30 11:30:29

+0

+1。但是'entry'似乎是一个OR映射对象,因此修改'entry.image'实际上会改变数据库中的对象(如果要提交事务)。所以我可能会做'render_template('show_entry.html',img = entry.image.encode('base64'))'并在模板中使用'img'。 – 2014-09-30 11:31:19