Flask RESTful api放错误

时间:2015-12-26 14:47:37

标签: python flask flask-restful

我有一个Post模型如下 -

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    likes = db.Column(db.Integer)
    body = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __init__(self, body, user_id):
        self.likes = 0
        self.body = body
        self.user_id = user_id

我无法使用PUT请求更新对象。这是我的代码 -

class UserPost(Resource):
    def get(self, post_id):
        print(post_id)
        return marshal(Post.query.get(post_id), post_fields)

    def put(self, post_id):
        post = Post.query.get_or_404(post_id)
        args = post_parser.parse_args()
        print args
        for k, v in args.iteritems():
            if v is not None:
                post.__dict__[k] = v

                db.session.add(post)
                db.session.commit()
        return marshal(post, post_fields)

Post对象未更新。

1 个答案:

答案 0 :(得分:1)

而不是手动更新post.__dict__使用setattr