我正在创建一个简单的Web api,其中flask
和sqlalchemy
用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()
当我尝试使用带有这样的邮递员的邮寄请求创建用户条目
{
"username":"test1",
"password":"test1pswd",
"user_role":"admin"
}
它在控制台上返回以下错误,
marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}
我在这里做什么错了?
答案 0 :(得分: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.']}
您可以:
对数据调用json.loads()
,然后传递给Schema.load
>>> 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'}