本文整理汇总了Python中marshmallow.Schema方法的典型用法代码示例。如果您正苦于以下问题:Python marshmallow.Schema方法的具体用法?Python marshmallow.Schema怎么用?Python marshmallow.Schema使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshmallow
的用法示例。
在下文中一共展示了marshmallow.Schema方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_api_register_field_parameters
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_api_register_field_parameters(self, app, mapping):
api = Api(app)
class CustomField(ma.fields.Field):
pass
api.register_field(CustomField, *mapping)
class Document(ma.Schema):
field = CustomField()
api.spec.components.schema('Document', schema=Document)
if len(mapping) == 2:
properties = {'field': {'type': 'custom string'}}
# If mapping format is None, it does not appear in the spec
if mapping[1] is not None:
properties['field']['format'] = mapping[1]
else:
properties = {'field': {'type': 'integer', 'format': 'int32'}}
assert get_schemas(api.spec)['Document'] == {
'properties': properties, 'type': 'object'}
示例2: test_use_kwargs_schema_with_post_load
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_use_kwargs_schema_with_post_load(self, app, client):
class User:
def __init__(self, name):
self.name = name
def update(self, name):
self.name = name
class ArgSchema(Schema):
name = fields.Str()
@post_load
def make_object(self, data, **kwargs):
return User(**data)
@app.route('/', methods=('POST', ))
@use_kwargs(ArgSchema())
def view(user):
assert isinstance(user, User)
return {'name': user.name}
data = {'name': 'freddie'}
res = client.post('/', data)
assert res.json == data
示例3: _generate_etag
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def _generate_etag(etag_data, etag_schema=None, extra_data=None):
"""Generate an ETag from data
etag_data: Data to use to compute ETag
etag_schema: Schema to dump data with before hashing
extra_data: Extra data to add before hashing
Typically, extra_data is used to add pagination metadata to the hash.
It is not dumped through the Schema.
"""
if etag_schema is None:
raw_data = etag_data
else:
if isinstance(etag_schema, type):
etag_schema = etag_schema()
raw_data = etag_schema.dump(etag_data)
if MARSHMALLOW_VERSION_MAJOR < 3:
raw_data = raw_data.data
if extra_data:
raw_data = (raw_data, extra_data)
# flask's json.dumps is needed here
# as vanilla json.dumps chokes on lazy_strings
data = json.dumps(raw_data, sort_keys=True)
return hashlib.sha1(bytes(data, 'utf-8')).hexdigest()
示例4: test_blueprint_response_response_object
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_blueprint_response_response_object(self, app, schemas):
api = Api(app)
blp = Blueprint('test', __name__, url_prefix='/test')
client = app.test_client()
@blp.route('/response')
# Schema is ignored when response object is returned
@blp.response(schemas.DocSchema, code=200)
def func_response():
return {}, 201, {'X-header': 'test'}
api.register_blueprint(blp)
response = client.get('/test/response')
assert response.status_code == 201
assert response.status == '201 CREATED'
assert response.json == {}
assert response.headers['X-header'] == 'test'
示例5: test_metadata
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_metadata():
"""Metadata should be available in the field definition."""
class TestSchema(Schema):
myfield = fields.String(metadata={"foo": "Bar"})
yourfield = fields.Integer(required=True, baz="waz")
schema = TestSchema()
dumped = validate_and_dump(schema)
props = dumped["definitions"]["TestSchema"]["properties"]
assert props["myfield"]["foo"] == "Bar"
assert props["yourfield"]["baz"] == "waz"
assert "metadata" not in props["myfield"]
assert "metadata" not in props["yourfield"]
# repeat process to assert idempotency
dumped = validate_and_dump(schema)
props = dumped["definitions"]["TestSchema"]["properties"]
assert props["myfield"]["foo"] == "Bar"
assert props["yourfield"]["baz"] == "waz"
示例6: test_nested_descriptions
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_nested_descriptions():
class TestNestedSchema(Schema):
myfield = fields.String(metadata={"description": "Brown Cow"})
yourfield = fields.Integer(required=True)
class TestSchema(Schema):
nested = fields.Nested(
TestNestedSchema, metadata={"description": "Nested 1", "title": "Title1"}
)
yourfield_nested = fields.Integer(required=True)
schema = TestSchema()
dumped = validate_and_dump(schema)
nested_def = dumped["definitions"]["TestNestedSchema"]
nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
assert nested_def["properties"]["myfield"]["description"] == "Brown Cow"
assert nested_dmp["$ref"] == "#/definitions/TestNestedSchema"
assert nested_dmp["description"] == "Nested 1"
assert nested_dmp["title"] == "Title1"
示例7: test_nested_string_to_cls
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_nested_string_to_cls():
class TestNamedNestedSchema(Schema):
foo = fields.Integer(required=True)
class TestSchema(Schema):
foo2 = fields.Integer(required=True)
nested = fields.Nested("TestNamedNestedSchema")
schema = TestSchema()
dumped = validate_and_dump(schema)
nested_def = dumped["definitions"]["TestNamedNestedSchema"]
nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
assert nested_dmp["type"] == "object"
assert nested_def["properties"]["foo"]["format"] == "integer"
示例8: test_deep_nested
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_deep_nested():
"""Test that deep nested schemas are in definitions."""
class InnerSchema(Schema):
boz = fields.Integer(required=True)
class InnerMiddleSchema(Schema):
baz = fields.Nested(InnerSchema, required=True)
class OuterMiddleSchema(Schema):
bar = fields.Nested(InnerMiddleSchema, required=True)
class OuterSchema(Schema):
foo = fields.Nested(OuterMiddleSchema, required=True)
schema = OuterSchema()
dumped = validate_and_dump(schema)
defs = dumped["definitions"]
assert "OuterSchema" in defs
assert "OuterMiddleSchema" in defs
assert "InnerMiddleSchema" in defs
assert "InnerSchema" in defs
示例9: test_respect_only_for_nested_schema
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_respect_only_for_nested_schema():
"""Should ignore fields not in 'only' metadata for nested schemas."""
class InnerRecursiveSchema(Schema):
id = fields.Integer(required=True)
baz = fields.String()
recursive = fields.Nested("InnerRecursiveSchema")
class MiddleSchema(Schema):
id = fields.Integer(required=True)
bar = fields.String()
inner = fields.Nested("InnerRecursiveSchema", only=("id", "baz"))
class OuterSchema(Schema):
foo2 = fields.Integer(required=True)
nested = fields.Nested("MiddleSchema")
schema = OuterSchema()
dumped = validate_and_dump(schema)
inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
assert "recursive" not in inner_props
示例10: test_respect_exclude_for_nested_schema
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_respect_exclude_for_nested_schema():
"""Should ignore fields in 'exclude' metadata for nested schemas."""
class InnerRecursiveSchema(Schema):
id = fields.Integer(required=True)
baz = fields.String()
recursive = fields.Nested("InnerRecursiveSchema")
class MiddleSchema(Schema):
id = fields.Integer(required=True)
bar = fields.String()
inner = fields.Nested("InnerRecursiveSchema", exclude=("recursive",))
class OuterSchema(Schema):
foo2 = fields.Integer(required=True)
nested = fields.Nested("MiddleSchema")
schema = OuterSchema()
dumped = validate_and_dump(schema)
inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
assert "recursive" not in inner_props
示例11: test_respect_dotted_exclude_for_nested_schema
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_respect_dotted_exclude_for_nested_schema():
"""Should ignore dotted fields in 'exclude' metadata for nested schemas."""
class InnerRecursiveSchema(Schema):
id = fields.Integer(required=True)
baz = fields.String()
recursive = fields.Nested("InnerRecursiveSchema")
class MiddleSchema(Schema):
id = fields.Integer(required=True)
bar = fields.String()
inner = fields.Nested("InnerRecursiveSchema")
class OuterSchema(Schema):
foo2 = fields.Integer(required=True)
nested = fields.Nested("MiddleSchema", exclude=("inner.recursive",))
schema = OuterSchema()
dumped = validate_and_dump(schema)
inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
assert "recursive" not in inner_props
示例12: test_nested_instance
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_nested_instance():
"""Should also work with nested schema instances"""
class TestNestedSchema(Schema):
baz = fields.Integer()
class TestSchema(Schema):
foo = fields.String()
bar = fields.Nested(TestNestedSchema())
schema = TestSchema()
dumped = validate_and_dump(schema)
nested_def = dumped["definitions"]["TestNestedSchema"]
nested_obj = dumped["definitions"]["TestSchema"]["properties"]["bar"]
assert "baz" in nested_def["properties"]
assert nested_obj["$ref"] == "#/definitions/TestNestedSchema"
示例13: test_unknown_typed_field
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_unknown_typed_field():
class Colour(fields.Field):
def _jsonschema_type_mapping(self):
return {"type": "string"}
def _serialize(self, value, attr, obj):
r, g, b = value
r = hex(r)[2:]
g = hex(g)[2:]
b = hex(b)[2:]
return "#" + r + g + b
class UserSchema(Schema):
name = fields.String(required=True)
favourite_colour = Colour()
schema = UserSchema()
dumped = validate_and_dump(schema)
assert dumped["definitions"]["UserSchema"]["properties"]["favourite_colour"] == {
"type": "string"
}
示例14: test_metadata_direct_from_field
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_metadata_direct_from_field():
"""Should be able to get metadata without accessing metadata kwarg."""
class TestSchema(Schema):
id = fields.Integer(required=True)
metadata_field = fields.String(description="Directly on the field!")
schema = TestSchema()
dumped = validate_and_dump(schema)
assert dumped["definitions"]["TestSchema"]["properties"]["metadata_field"] == {
"title": "metadata_field",
"type": "string",
"description": "Directly on the field!",
}
示例15: test_dumps_iterable_enums
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import Schema [as 别名]
def test_dumps_iterable_enums():
mapping = {"a": 0, "b": 1, "c": 2}
class TestSchema(Schema):
foo = fields.Integer(
validate=validate.OneOf(mapping.values(), labels=mapping.keys())
)
schema = TestSchema()
dumped = validate_and_dump(schema)
assert dumped["definitions"]["TestSchema"]["properties"]["foo"] == {
"enum": [v for v in mapping.values()],
"enumNames": [k for k in mapping.keys()],
"format": "integer",
"title": "foo",
"type": "number",
}