作者:烧饼来一个则_815 | 来源:互联网 | 2023-09-02 18:47
我正在尝试使用flask-restful使restapi成为我正在使用flask-sqlalchemy作为ORM的地方.这是我的模型类.classPost(db.Model):__
我正在尝试使用flask-restful使rest api成为我正在使用flask-sqlalchemy作为ORM的地方.这是我的模型类.
class Post(db.Model):
__tablename__ = 'post'
postid = db.Column(db.Integer,primary_key=True)
post = db.Column(db.String(64))
userid = db.Column(db.Integer,db.ForeignKey('user.userid'))
#serialize property used for serializing this class to JSON
@property
def serialize(self):
return {
'postid': self.postid,
'post': self.post,
'author':self.author
}
和
class User(db.Model):
userid = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(30))
email = db.Column(db.String(20))
posts = db.relationship('Post',backref="author",lazy='dynamic')
#serialize property used for serializing this class to JSON
@property
def serialize(self):
return {
'username': self.username,
'email': self.email
}
然后填充数据库.现在我正在尝试从中制作json
class PostList(Resource):
def get(self):
posts = DL_models.Post.query.all()
posts = [post.serialize for post in posts]
return { 'posts': posts }
api.add_resource(PostList, '/twitter/api/v1.0/posts', endpoint = 'posts')
当我将Post中的序列化方法更改为
@property
def serialize(self):
return {
'postid': self.postid,
'post': self.post,
'author':self.postid
}
这将返回预期的json输出,但是当我更改为’author’:self.author时,出现错误
TypeError: is not JSON serializable
我知道我也必须对那些嵌套对象调用序列化,但是我不知道该怎么做.
或者,请分享您的经验以在sqlalchemy中编码关系.
解决方法:
由于您已经在使用Flask-Restful,您是否考虑过使用其内置的data marshaling solution?
但是,对于封送复杂的数据结构,我发现Marshmallow的任务性能要好上千倍,甚至可以简化嵌套序列化程序在其他程序中的工作.还有一个Flask扩展,用于检查端点和输出URL.