4

我试图用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: <app.DL_models.User object at 0x7f263f3adc10> is not JSON serializable

我知道我也必须对那些嵌套对象调用序列化,但我不知道该怎么做。

或者请分享您在 sqlalchemy 中编码关系的经验。

4

2 回答 2

4

既然您已经在使用 Flask-Restful,您是否考虑过使用他们内置的数据封送解决方案

然而,对于编组复杂的数据结构,我发现Marshmallow完成任务的能力要好一千倍,甚至使嵌套序列化器在其他序列化器中变得容易。还有一个 Flask 扩展,旨在检查端点和输出 URL。

于 2014-09-10T01:21:14.003 回答
0

这是一个平底船,但你试过下面的吗?

“作者”:self.author.username

从错误消息中我猜它正在发送给用户,但不知道你想要什么。

于 2014-09-09T07:46:01.617 回答