用棉花糖中的数据更新行(SQLAlchemy) [英] Update row (SQLAlchemy) with data from marshmallow

查看:70
本文介绍了用棉花糖中的数据更新行(SQLAlchemy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask,Flask-SQLAlchemy,Flask-Marshmallow + marshmallow-sqlalchemy,尝试实现REST api PUT方法.我还没有找到任何使用SQLA和棉花糖实现更新的教程.

I'm using Flask, Flask-SQLAlchemy, Flask-Marshmallow + marshmallow-sqlalchemy, trying to implement REST api PUT method. I haven't found any tutorial using SQLA and Marshmallow implementing update.

这是代码:

class NodeSchema(ma.Schema):
    # ...


class NodeAPI(MethodView):
    decorators = [login_required, ]
    model = Node

    def get_queryset(self):
        if g.user.is_admin:
            return self.model.query
        return self.model.query.filter(self.model.owner == g.user)

    def put(self, node_id):
        json_data = request.get_json()
        if not json_data:
            return jsonify({'message': 'Invalid request'}), 400

        # Here is part which I can't make it work for me
        data, errors = node_schema.load(json_data)
        if errors:
            return jsonify(errors), 422

        queryset = self.get_queryset()


        node = queryset.filter(Node.id == node_id).first_or_404()
        # Here I need some way to update this object
        node.update(data) #=> raises AttributeError: 'Node' object has no attribute 'update'

        # Also tried:
        # node = queryset.filter(Node.id == node_id)
        # node.update(data) <-- It doesn't if know there is any object
        # Wrote testcase, when user1 tries to modify node of user2. Node doesn't change (OK), but user1 gets status code 200 (NOT OK).

        db.session.commit()
        return jsonify(), 200

推荐答案

更新

marshmallow-sqlalchemy代替Flask-Marshmallow扩展ModelSchema,您具有:

load(data, session=None, instance=None, *args, **kwargs)

然后,您必须将正在编辑的对象作为参数传递给schema.load(),如下所示:

Then you have to pass the object being edited as parameter in schema.load(), like this:

node_schema.load(json_data, instance=Node().query.get(node_id))

如果要在没有Model的所有必填字段的情况下加载,则可以添加partial=True,如下所示:

And if you want to load without all required fields of Model, you can add the partial=True, like this:

node_schema.load(json_data, instance=Node().query.get(node_id), partial=True)

请参阅文档 marshmallow_sqlalchemy.ModelSchema.load

这篇关于用棉花糖中的数据更新行(SQLAlchemy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆