marshal_with用于Flask RESTful中SQLAlchemy对象的列表



我试图在使用flask_restful中的marshal_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)

API对PersonControllerget请求的响应如下:

{
"id": 1,
"name": "Leo",
"pets": [
{
"id": 1,
"name": "Spoc"
}
]
}

但对于PersonListControllerget请求,我得到空响应为:

[
{
"items": null
},
{
"items": null
}
]

有谁能帮我一下这个问题吗?

我认为使用flask-retx会更方便marshal_list_with.

@api.marshal_list_with(_user, envelope='data')
def get(self):
"""List all registered users"""
return get_all_users()

相关内容

  • 没有找到相关文章

最新更新