Python 在Flask RESTful中为SQLAlchemy对象列表封送\u
我正在尝试使用Python 在Flask RESTful中为SQLAlchemy对象列表封送\u,python,flask,flask-sqlalchemy,marshalling,flask-restful,Python,Flask,Flask Sqlalchemy,Marshalling,Flask Restful,我正在尝试使用flask\u restful中的marshall\u with序列化JSON中的SQLAlchemy对象列表。对于单个对象,它对我有效 from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_restful import Resource, Api, marshal_with, reqparse, fields app = Flask(__name__) db = SQLAlchemy
flask\u restful
中的marshall\u with
序列化JSON中的SQLAlchemy对象列表。对于单个对象,它对我有效
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api, marshal_with, reqparse, fields
app = Flask(__name__)
db = SQLAlchemy(app)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30), nullable=False)
pets = db.relationship('Pet', backref='owner')
def __init__(self,name):
self.name = name
@classmethod
def find_by_id(cls, id):
return cls.query.filter_by(id=id).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
class Pet(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), nullable=False)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
def __init__(self,name,owner_id):
self.name = name
self.owner_id = owner_id
@classmethod
def find_by_id(cls, id):
return cls.query.filter_by(id=id).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
pet_serializer = {
'id':fields.Integer,
'name':fields.String
}
person_serializer = {
'id':fields.Integer,
'name':fields.String,
'pets':fields.Nested(pet_serializer)
}
person_list_serializer = {
'items':fields.List(fields.Nested(person_serializer))
}
class PersonController(Resource):
@marshal_with(person_serializer)
def get(self,id):
person = Person.find_by_id(id)
if person:
return person, 200
else:
return {'msg':'Resource not found'}, 404
class PersonListController(Resource):
@marshal_with(person_list_serializer)
def get(self):
return Person.query.all()
api.add_resource(PersonController, '/person/<int:id>')
api.add_resource(PersonListController, '/persons')
if __name__ == '__main__':
app.run(debug=True, port=5000)
但是对于PersonListController
get
请求,我得到的是空响应,如下所示:
[
{
"items": null
},
{
"items": null
}
]
请任何人在这里帮助我解决这个问题。数据应该是:`{“items”:[person\u json,person\u json]}``?是的,你说得对@黄
[
{
"items": null
},
{
"items": null
}
]