本文整理汇总了Python中marshmallow.fields.List方法的典型用法代码示例。如果您正苦于以下问题:Python fields.List方法的具体用法?Python fields.List怎么用?Python fields.List使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshmallow.fields
的用法示例。
在下文中一共展示了fields.List方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _validate_marshmallow_type
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def _validate_marshmallow_type(self, field_cfg):
"""Make sure the Marshmallow type is one we support."""
def validate_basic_marshmallow_type(_type):
allowed_types = [
Bool, DateString, Integer, SanitizedUnicode
]
assert any([
isinstance(_type, allowed_type) for allowed_type
in allowed_types
])
marshmallow_type = field_cfg["marshmallow"]
if isinstance(marshmallow_type, List):
validate_basic_marshmallow_type(marshmallow_type.inner)
else:
validate_basic_marshmallow_type(marshmallow_type)
示例2: test_list_nested
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_list_nested():
"""Test that a list field will work with an inner nested field."""
class InnerSchema(Schema):
foo = fields.Integer(required=True)
class ListSchema(Schema):
bar = fields.List(fields.Nested(InnerSchema), required=True)
schema = ListSchema()
dumped = validate_and_dump(schema)
nested_json = dumped["definitions"]["ListSchema"]["properties"]["bar"]
assert nested_json["type"] == "array"
assert "items" in nested_json
item_schema = nested_json["items"]
assert "InnerSchema" in item_schema["$ref"]
示例3: revocation_registries_created
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def revocation_registries_created(request: web.BaseRequest):
"""
Request handler to get revocation registries that current agent created.
Args:
request: aiohttp request object
Returns:
List of identifiers of matching revocation registries.
"""
context = request.app["request_context"]
search_tags = [
tag for tag in vars(RevRegsCreatedQueryStringSchema)["_declared_fields"]
]
tag_filter = {
tag: request.query[tag] for tag in search_tags if tag in request.query
}
found = await IssuerRevRegRecord.query(context, tag_filter)
return web.json_response({"rev_reg_ids": [record.revoc_reg_id for record in found]})
示例4: schema
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def schema(**kwargs):
"""
Create a schema. Mostly useful for creating single-use schemas on-the-fly.
"""
items = list(kwargs.items())
if len(items) != 1 or not isinstance(items[0][1], dict):
raise RuntimeError('schema required 1 keyword argument of type dict')
name, spec = items[0]
schema_dict = {}
for key, value in spec.items():
cls, description = value if isinstance(value, tuple) else (value, None)
required = key.endswith('*')
key = key.rstrip('*')
kwargs = {'required': required, 'description': description}
if isinstance(cls, SchemaMeta):
schema_dict[key] = Nested(cls, required=required)
elif isinstance(cls, list) and len(cls) == 1:
cls = cls[0]
schema_dict[key] = List(Nested(cls), **kwargs) if isinstance(cls, SchemaMeta) else List(cls, **kwargs)
else:
schema_dict[key] = cls.__call__(**kwargs) if callable(cls) else cls
return type(name, (Schema,), schema_dict)
示例5: test_accepts_with_postional_args_query_params_schema_and_header_schema
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_accepts_with_postional_args_query_params_schema_and_header_schema(app, client): # noqa
class QueryParamsSchema(Schema):
query_param = fields.List(fields.String(), required=True)
class HeadersSchema(Schema):
Header = fields.Integer(required=True)
@app.route("/test")
@accepts(
dict(name="foo", type=int, help="An important foo"),
query_params_schema=QueryParamsSchema,
headers_schema=HeadersSchema)
def test():
assert request.parsed_args["foo"] == 3
assert request.parsed_query_params["query_param"] == ["baz", "qux"]
assert request.parsed_headers["Header"] == 3
return "success"
with client as cl:
resp = cl.get("/test?foo=3&query_param=baz&query_param=qux", headers={"Header": "3"})
assert resp.status_code == 200
示例6: test_multidict_list_values_interpreted_correctly
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_multidict_list_values_interpreted_correctly(app, client): # noqa
class TestSchema(Schema):
name = fields.List(fields.String(), required=True)
multidict = MultiDict([
("name", "value"),
("new_value", "still_here")
])
result = _convert_multidict_values_to_schema(multidict, TestSchema())
# `name` should be converted to a list.
assert result["name"] == ["value"]
# `new_value` should *not* be removed here, even though it"s not in the schema.
assert result["new_value"] == "still_here"
# Also makes sure handling a list with >1 values also works.
multidict = MultiDict([
("name", "value"),
("name", "value2"),
])
result = _convert_multidict_values_to_schema(multidict, TestSchema())
assert result["name"] == ["value", "value2"]
示例7: test_using_as_nested_schema
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_using_as_nested_schema(self):
class SchemaWithList(m.Schema):
items = f.List(f.Nested(MySchema))
schema = SchemaWithList()
result = schema.load(
{
"items": [
{"type": "Foo", "value": "hello world!"},
{"type": "Bar", "value": 123},
]
}
)
assert {"items": [Foo("hello world!"), Bar(123)]} == result
with pytest.raises(m.ValidationError) as exc_info:
schema.load(
{"items": [{"type": "Foo", "value": "hello world!"}, {"value": 123}]}
)
assert {"items": {1: {"type": [REQUIRED_ERROR]}}} == exc_info.value.messages
示例8: _process_dict_values
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def _process_dict_values(value: Any) -> Any:
"""Process a returned from a JSON response.
Args:
value: A dict, list, or value returned from a JSON response.
Returns:
Either an UnknownModel, a List of processed values, or the original value \
passed through.
"""
if isinstance(value, Mapping):
return UnknownModel(**value)
elif isinstance(value, list):
return [_process_dict_values(v) for v in value]
else:
return value
示例9: schemas
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def schemas():
class ParentSchema(Schema):
id = fields.Integer(as_string=True)
name = fields.String(required=True)
children = RelatedItem("ChildSchema", many=True, exclude=("parent",))
child_ids = fields.List(fields.Integer(as_string=True), load_only=True)
class ChildSchema(Schema):
@classmethod
def get_query_options(cls, load):
return (load.joinedload("parent"),)
id = fields.Integer(as_string=True)
name = fields.String(required=True)
parent = RelatedItem(
ParentSchema, exclude=("children",), allow_none=True
)
parent_id = fields.Integer(
as_string=True, allow_none=True, load_only=True
)
return {"parent": ParentSchema(), "child": ChildSchema()}
示例10: schemas
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def schemas():
class NameSchema(Schema):
name = fields.String(required=True)
class NameListSchema(Schema):
names = fields.List(fields.String(), data_key="name", required=True)
class NameDelimitedListSchema(Schema):
names = DelimitedList(fields.String(), data_key="name", required=True)
class NameDefaultSchema(Schema):
name = fields.String(missing="foo")
return {
"name": NameSchema(),
"name_list": NameListSchema(),
"name_delimited_list": NameDelimitedListSchema(),
"name_default": NameDefaultSchema(),
}
示例11: create_app
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def create_app(self):
app = Flask(__name__)
Rebar().init_app(app=app)
class NestedSchema(validation.RequestSchema):
baz = fields.List(fields.Integer())
class Schema(validation.RequestSchema):
foo = fields.Integer(required=True)
bar = fields.Email()
nested = fields.Nested(NestedSchema)
@app.route("/stuffs", methods=["POST"])
def json_body_handler():
data = get_json_body_params_or_400(schema=Schema)
return response(data)
return app
示例12: test_override_container_type_with_type_mapping
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_override_container_type_with_type_mapping(self):
type_mapping = [
(List, fields.List, List[int]),
(Dict, fields.Dict, Dict[str, int]),
(Tuple, fields.Tuple, Tuple[int, str, bytes]),
]
for base_type, marshmallow_field, schema in type_mapping:
class MyType(marshmallow_field):
...
self.assertIsInstance(field_for_schema(schema), marshmallow_field)
class BaseSchema(Schema):
TYPE_MAPPING = {base_type: MyType}
self.assertIsInstance(
field_for_schema(schema, base_schema=BaseSchema), MyType
)
示例13: test_use_type_mapping_from_base_schema
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_use_type_mapping_from_base_schema(self):
class CustomType:
pass
class CustomField(Field):
pass
class CustomListField(ListField):
pass
class BaseSchema(Schema):
TYPE_MAPPING = {CustomType: CustomField, typing.List: CustomListField}
@dataclasses.dataclass
class WithCustomField:
custom: CustomType
custom_list: typing.List[float]
uuid: UUID
n: int
schema = class_schema(WithCustomField, base_schema=BaseSchema)()
self.assertIsInstance(schema.fields["custom"], CustomField)
self.assertIsInstance(schema.fields["custom_list"], CustomListField)
self.assertIsInstance(schema.fields["uuid"], UUIDField)
self.assertIsInstance(schema.fields["n"], Integer)
示例14: test_list
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def test_list():
class ListSchema(Schema):
foo = fields.List(fields.String(), required=True)
schema = ListSchema()
dumped = validate_and_dump(schema)
nested_json = dumped["definitions"]["ListSchema"]["properties"]["foo"]
assert nested_json["type"] == "array"
assert "items" in nested_json
item_schema = nested_json["items"]
assert item_schema["type"] == "string"
示例15: _from_python_type
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import List [as 别名]
def _from_python_type(self, obj, field, pytype):
"""Get schema definition from python type."""
json_schema = {"title": field.attribute or field.name}
for key, val in PY_TO_JSON_TYPES_MAP[pytype].items():
json_schema[key] = val
if field.dump_only:
json_schema["readonly"] = True
if field.default is not missing:
json_schema["default"] = field.default
if field.allow_none:
previous_type = json_schema["type"]
json_schema["type"] = [previous_type, "null"]
# NOTE: doubled up to maintain backwards compatibility
metadata = field.metadata.get("metadata", {})
metadata.update(field.metadata)
for md_key, md_val in metadata.items():
if md_key in ("metadata", "name"):
continue
json_schema[md_key] = md_val
if isinstance(field, fields.List):
json_schema["items"] = self._get_schema_for_field(obj, list_inner(field))
return json_schema