使用Marshmallow模式过滤SQLAlchemy表更新

4
我正在使用Flask开发API,使用Marshmallow进行序列化/反序列化/验证,并使用SQLAlchemy作为ORM。
在我的更新功能中,我想限制可以更新的字段,例如,我不希望用户目前能够更改他们的电子邮件。
为了实现这一点,我设置了一个模式(UserSchema),其字段由元组(UserSchemaTypes.UPDATE_FIELDS)限制。该元组不包括电子邮件。
我遇到的问题是我的数据库中的User行需要电子邮件作为必填字段。
因此,当我使用模式创建一个User模型对象(users_schema.load(user_json))时,将向SQLAlchemy会话添加一个非法对象。
#schema to validate the posted fields against  
users_schema = UserSchema(only=UserSchemaTypes.UPDATE_FIELDS)
#attempt to deserialize the posted json to a User model object using the schema
user_data = users_schema.load(user_json)
if not user_data.errors:#update data passed validation
   user_update_obj = user_data.data 
   User.update(user_id,vars(user_update_obj))

在我的更新函数中,我需要通过 db.session.expunge_all() 从会话中删除这个非法的对象,否则我会收到操作错误。
@staticmethod    
def update(p_id,data):
    db.session.expunge_all()#hack I want to remove
    user = User.query.get(p_id)
    for k, v in data.iteritems():
        setattr(user, k, v)
    db.session.commit()

当删除db.session.expunge_all()时收到OperationalError错误:
OperationalError: (raised as a result of Query-invoked autoflush; consider        
using a session.no_autoflush block if this flush is occurring prematurely) 
(_mysql_exceptions.OperationalError) (1048, "Column 'email' cannot be   null") [SQL: u'INSERT INTO user (email, password, active, phone, current_login_at, last_login_at, current_login_ip, last_login_ip, login_count) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)'] [parameters: (None, None, 1, '0444', None, None, None, None, None)]

有没有更好/更干净的方法来做这个?
2个回答

1

来自Steven Loria的消息 https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/33#issuecomment-147008000

以下是几种可能的方法:

选项1:字段参数

from marshmallow import Schema, fields, pre_load

class BaseSchema(Schema):
    @pre_load
    def check_update_fields(self, data)
        non_update_fields = set([
            fname, fobj for fname, obj in self.fields
            if fobj.metadata.get('can_update') is False
        ])
        return {
            key: value for key, value in data.items()
            if key not in non_update_fields
        }

class UserSchema(BaseSchema):
    name = fields.Str()
    email = fields.Str(can_update=False)

选项2:class Meta 选项
from marshmallow import Schema, SchemaOpts, fields, pre_load
class BaseSchemaOpts(SchemaOpts):
    def __init__(self, meta):
        super().__init__(meta)
        self.update_fields = getattr(meta, 'update_fields', set())

class BaseSchema(Schema):
    OPTIONS_CLASS = BaseSchemaOpts

    email = fields.Str(can_update=False)

    @pre_load
    def check_update_fields(self, data)
        non_update_fields = set(self.fields) - set(self.opts.update_fields)
        return {
            key: value for key, value in data.items()
            if key not in non_update_fields
        }

class UserSchema(BaseSchema):

    name = fields.Str()
    email = fields.Str()

    class Meta:
        update_fields = ('name', )

0

您的数据库与模型不匹配。

由于您更改了模型(例如将电子邮件从 null 更改为 not null),因此应同步数据库。您可以删除表并重新同步数据库,或使用迁移工具修改表以使其与模型匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接