Reputation: 533
Hello I'm developing small app in python using flask, jinja2, sqlalchemy,... I'm saving binare data in my database:
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()
and i want to show the entry in my app:
@app.route('/recipe/<id>', methods=['GET', 'POST'])
def show_entry(id):
return render_template('show_entry.html', entry=db_session.query(Recipe).get(id))
And in my template i have:
<img src="data:image/png;base64,{{ entry.image }}"/>
But i have unicode error
UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)
Can you help me how to solve this?
Upvotes: 5
Views: 4051
Reputation: 87084
data:image/png;base64,
says that the PNG data is base64 encoded, so I think that you need to base64 encode the image data before rendering the template. If you do that, the encoding error should go away. Something like this should do the trick:
@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)
I'm not overly familiar with this, it could be a dict lookup?, i.e.
entry['image'] = entry['image'].encode('base64')
Upvotes: 4