'Flask TypeError TypeError: a bytes-like object is required, not 'NoneType'
I want to add images into sqlalchemy in flask and I tried to do it from this post.
from flask import Flask,render_template,request,Response
from flask_sqlalchemy import SQLAlchemy
from base64 import b64encode
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users1.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Images(db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.Text)
img = db.Column(db.Text)
db.create_all()
mylist = []
@app.route('/',methods=['POST','GET'])
def home():
if request.method == 'POST':
img1 = request.files['ab']
imager = img1.save(secure_filename(img1.filename))
imager = Images(name='abc',img=img1.read())
db.session.add(imager)
db.session.commit()
return render_template('other.html')
@app.route('/allimages',methods=['POST','GET'])
def home1():
mylist1 = Images.query.filter_by(name='abc').all()
for i in mylist1:
image = b64encode(i.img)
return render_template('new.html',posts=image)
if __name__ == '__main__':
app.run(debug=True)
But when I go to allimages I get TypeError TypeError: a bytes-like object is required, not 'NoneType'. What should I do? I get the error in the browser and also in the console.
Thanks.
Solution 1:[1]
Looks like you forgot to use the decode method of b64encode.
But also you're overwriting image, each time in the for loop. Going by the linked question you should be adding a new attribute to each image in images, in this case uri_src:
images = Images.query.filter_by(name='abc').all()
for image in images:
image.uri_src = b64encode(image.img).decode('utf-8')
# Now pass images (plural) to the template
return render_template('new.html',posts=images)
Then handle this in the template like:
{% for image in posts %}
<p>Name: {{ image.name }}</p>
<p>Image: </p> <img src="data:;base64,{{ image.uri_src }}">
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | v25 |
