'Flask SQLAlchemy Add Images

I want to add into a sqlalchemy database an image where a user uploads one. I tried to do it with this StackOverFlow [post].(Serve image stored in SQLAlchemy LargeBinary column)

Here is the flask code:

from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
from base64 import b64encode
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.String(200))
    img = db.Column(db.LargeBinary)

db.create_all()
mylist = []
@app.route('/',methods=['POST','GET'])
def home():
    if request.method == 'POST':
        img1 = request.files['ab']
        imager = Images(name='abc',img=img1)
        db.session.add(imager)
        db.session.commit()
    return render_template('other.html')

@app.route('/allimg',methods=['POST','GET'])
def home1():
    mylist1 = Images.query.filter_by(name='abc').all()
    event = Images.query.get_or_404(id)
    image = b64encode(event.img)
    return render_template('new.html',posts=image)
if __name__ == '__main__':
    app.run(debug=True)

Other.html

<form action='' method='post'  enctype="multipart/form-data">
    <button><input type='file' name='ab' id='file-input' multiple></button>
  </form>

New.html

<html>
    <body>
        {%for i in posts%}
        <img src="data:;base64,{{ logo }}"/>
        {%endfor%}
    </body>
</html>

When I go to allimg (The page that I show all images) I get

sqlalchemy.exc.InterfaceError
sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type.
[SQL: SELECT images.id AS images_id, images.name AS images_name, images.img AS images_img 
FROM images 
WHERE images.id = ?]
[parameters: (<built-in function id>,)]
(Background on this error at: https://sqlalche.me/e/14/rvf5)

Please answer.

Thanks.



Solution 1:[1]

Serve image stored in SQLAlchemy LargeBinary column

@app.route('/event/<int:id>/logo')
def event_logo(id):
    event = Event.query.get_or_404(id)
    image = b64encode(event.logo)
    return render_template('event.html', event=event, logo=image)

id in this context is comming in as an int parameter

your passing in id as (<built-in function id>,) from here https://docs.python.org/3/library/functions.html#id

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 anthony lutjen