T
T
tarp202021-03-03 18:31:37
Flask
tarp20, 2021-03-03 18:31:37

Flask. TypeError: Object of type Product is not JSON serializable?

main.py :

from flask_cors import CORS
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy

from sqlalchemy import UniqueConstraint

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:[email protected]/main'
CORS(app)

db = SQLAlchemy(app)


class Product(db.Model):

    id = db.Column(db.Integer, primary_key=True, autoincrement=False)
    title = db.Column(db.String(200))
    image = db.Column(db.String(200))


class ProductUser(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    product_id = db.Column(db.Integer)

    UniqueConstraint('user_id', 'product_id', name='user_product_unique')


@app.route('/api/products')
def index():
    return jsonify(Product.query.all())

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Yakushenko, 2021-03-03
@tarp20

jsonify does not know how to serialize classes, first you need to prepare the information:

data = [{'id': p.id, 'uid': p.user_id, 'pid': p.product_id} for p in Product.query.all()]
return jsonify(data)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question