新版 marshmallow 将 Field 中,非保留的关键参数都建议放入到 metadata
参数中,
没有放入的会显示 warning 。
示例代码:
# schemas.py
from marshmallow import Schema
from marshmallow import fields
class FooSchema(Schema):
name = fields.String(
required=True,
title='foo',
description='foo name')
relationship = fields.String(
title='bar', description='foobar')
测试代码:
from schemas import FooSchema
def test_warn():
INPUT = {
'name': 'something',
'relationship': 'others'
}
schema = FooSchema()
data = schema.load(INPUT)
assert data == INPUT
示例代码文件结构:
. ├── requirements.txt # marshmallow==3.3.0 ├── schemas.py └── test_warning.py
升级 marshmallow:
$ pip install -U marshmallow
...
Successfully installed marshmallow-3.14.1
使用 pytest 测试(出现 marshmallow warning ):
pytest test_warning.py
================================================================ test session starts =================================================================
platform darwin -- Python 3.8.3, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /private/tmp/_
collected 1 item
test_warning.py . [100%]
================================================================== warnings summary ==================================================================
.venv/lib/python3.8/site-packages/marshmallow/fields.py:218
/private/tmp/_/.venv/lib/python3.8/site-packages/marshmallow/fields.py:218: RemovedInMarshmallow4Warning: Passing field metadata as keyword arguments is deprecated. Use the explicit `metadata=...` argument instead. Additional metadata: {'title': 'foo', 'description': 'foo name'}
warnings.warn(
.venv/lib/python3.8/site-packages/marshmallow/fields.py:218
/private/tmp/_/.venv/lib/python3.8/site-packages/marshmallow/fields.py:218: RemovedInMarshmallow4Warning: Passing field metadata as keyword arguments is deprecated. Use the explicit `metadata=...` argument instead. Additional metadata: {'title': 'bar', 'description': 'foobar'}
warnings.warn(
-- Docs: https://docs.pytest.org/en/stable/warnings.html
=========================================================== 1 passed, 2 warnings in 0.03s ============================================================
修改为没有 warning 的代码:
...
class FooSchema(Schema):
name = fields.String(
required=True,
metadata={'title': 'foo', 'description': 'foo name'})
relationship = fields.String(
metadata={'title': 'bar', 'description': 'foobar'})
问题:
如果有很多个 fields.XXXFieldYYY(...)
代码,
一个一个手动修改起来太难了,
有没有什么快捷的方案一次性改好?
1
SmiteChow 2021-12-08 15:27:17 +08:00
|