Flask-Marshmallow 模式上的 ValidationError

ValidationError on Flask-Marshmallow schema

我正在创建一个简单的网络 api,使用 flasksqlalchemy,使用 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 请求创建用户条目时 postman 像这样

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

它 returns 在控制台上出现以下错误,

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

我做错了什么?

您正在尝试使用 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'}