【问题标题】:ValidationError on Flask-Marshmallow schemaFlask-Marshmallow 模式上的 ValidationError
【发布时间】:2019-09-16 09:19:30
【问题描述】:

我正在使用flasksqlalchemy 创建一个简单的Web api,并使用marshmallow 作为序列化程序,这里是UserModel

class UserModel(db.Model):
    __tablename__ = 'users'

    id            = db.Column(db.Integer, primary_key = True)
    username      = db.Column(db.String(120), unique = True, nullable = False)
    password      = db.Column(db.String(120), nullable = False)
    user_role     = db.Column(db.String(10), nullable = False)
    access_token  = db.Column(db.String(120), unique = True, nullable = True, default='as' )
    refresh_token = db.Column(db.String(120), unique = True, nullable = True, default='as' )

和架构,

class UserSchema(Schema):
    username = fields.Str()
    password = fields.Str()
    user_role = fields.Str()
    access_token = fields.Str()
    refresh_token = fields.Str()

当我尝试使用像这样的邮递员使用 post 请求创建用户条目时

{
    "username":"test1",
    "password":"test1pswd",
    "user_role":"admin"
}

它在控制台上返回以下错误,

marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}

我在这里做错了什么?

【问题讨论】:

    标签: python marshmallow


    【解决方案1】:

    您正在尝试使用 Schema.load 方法加载 json。

    >>> import json
    >>> import marshmallow as mm
    >>> class S(mm.Schema):               
    ...     username = mm.fields.Str()
    ...     password = mm.fields.Str()
    ...     user_role = mm.fields.Str()
    ...     access_token = mm.fields.Str()
    ...     refresh_token = mm.fields.Str()
    ... 
    >>> d = {'username': 'test1', 'password': 'test1pswd', 'user_role': 'admin'}
    
    >>> S().load(json.dumps(d))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/kdwyer/.virtualenvs/so37/lib/python3.7/site-packages/marshmallow/schema.py", line 681, in load
        data, many=many, partial=partial, unknown=unknown, postprocess=True
      File "/home/kdwyer/.virtualenvs/so37/lib/python3.7/site-packages/marshmallow/schema.py", line 840, in _do_load
        raise exc
    marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}
    

    你可以:

    在传递给Schema.load之前对数据调用json.loads()

    >>> S().load(json.loads(json.dumps(d)))
    {'password': 'test1pswd', 'user_role': 'admin', 'username': 'test1'}
    

    将json传递给Schema.loads进行自动反序列化

    >>> S().loads(json.dumps(d))
    {'password': 'test1pswd', 'user_role': 'admin', 'username': 'test1'}
    

    【讨论】:

    • 在我来到这里之前,我浪费了大约 1 个小时来弄清楚我的代码有什么问题。我正在发送一个json数据。我刚刚删除了 json 格式并发送了正常数据,它工作了
    • 对我来说,我收到了List,必须设置SomeSchema(many=True)
    • 可能是一个愚蠢的问题,但与其将 dict d 转储为 JSON 字符串,然后从 JSON 字符串重新创建一个 dict,为什么不直接做 S().load(d)
    • @chrisinmtown 是的,这会起作用 - 我想当我回答时我不想假设原始的dict 可用:提问者可能只有一个 JSON 字符串。但是,是的,如果您有原始对象,那么往返到 JSON 并返回是多余的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2018-07-14
    • 2020-06-17
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多