本文整理汇总了Python中marshmallow.fields.Field方法的典型用法代码示例。如果您正苦于以下问题:Python fields.Field方法的具体用法?Python fields.Field怎么用?Python fields.Field使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshmallow.fields
的用法示例。
在下文中一共展示了fields.Field方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_unknown_typed_field
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [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"
}
示例2: handle_one_of
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def handle_one_of(schema, field, validator, parent_schema):
"""Adds the validation logic for ``marshmallow.validate.OneOf`` by setting
the JSONSchema `enum` property to the allowed choices in the validator.
Args:
schema (dict): The original JSON schema we generated. This is what we
want to post-process.
field (fields.Field): The field that generated the original schema and
who this post-processor belongs to.
validator (marshmallow.validate.OneOf): The validator attached to the
passed in field.
parent_schema (marshmallow.Schema): The Schema instance that the field
belongs to.
Returns:
dict: New JSON Schema that has been post processed and
altered.
"""
schema["enum"] = list(validator.choices)
schema["enumNames"] = list(validator.labels)
return schema
示例3: test__ma_field_to_fr_field_converts_metadata_param_to_description_if_present
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def test__ma_field_to_fr_field_converts_metadata_param_to_description_if_present():
@dataclass
class FakeFieldWithDescription(ma.Field):
metadata: dict
expected_description = "test"
fr_field_dict = utils._ma_field_to_fr_field(
FakeFieldWithDescription(metadata={"description": expected_description})
)
assert fr_field_dict["description"] == expected_description
@dataclass
class FakeFieldNoMetaData(ma.Field):
pass
fr_field_dict = utils._ma_field_to_fr_field(FakeFieldNoMetaData())
assert "description" not in fr_field_dict
@dataclass
class FakeFieldNoDescription(ma.Field):
metadata: dict
fr_field_dict = utils._ma_field_to_fr_field(FakeFieldNoDescription(metadata={}))
assert "description" not in fr_field_dict
示例4: test__ma_field_to_fr_field_converts_default_to_example_if_present
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def test__ma_field_to_fr_field_converts_default_to_example_if_present():
@dataclass
class FakeFieldWithDefault(ma.Field):
default: str
expected_example_value = "test"
fr_field_dict = utils._ma_field_to_fr_field(
FakeFieldWithDefault(default=expected_example_value)
)
assert fr_field_dict["example"] == expected_example_value
@dataclass
class FakeFieldNoDefault(ma.Field):
pass
fr_field_dict = utils._ma_field_to_fr_field(FakeFieldNoDefault())
assert "example" not in fr_field_dict
示例5: _ma_field_to_fr_field
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def _ma_field_to_fr_field(value: ma.Field) -> dict:
fr_field_parameters = {}
if hasattr(value, "default"):
fr_field_parameters["example"] = value.default
if hasattr(value, "required"):
fr_field_parameters["required"] = value.required
if hasattr(value, "metadata") and "description" in value.metadata:
fr_field_parameters["description"] = value.metadata["description"]
if hasattr(value, "missing") and type(value.missing) != ma.utils._Missing:
fr_field_parameters["default"] = value.missing
return fr_field_parameters
示例6: ma_field_to_reqparse_argument
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def ma_field_to_reqparse_argument(value: ma.Field) -> dict:
"""Maps a marshmallow field to a dictionary that can be used to initialize a
request parser argument.
"""
reqparse_argument_parameters = {}
if is_list_field(value):
value_type = type(value.inner)
reqparse_argument_parameters["action"] = "append"
else:
value_type = type(value)
reqparse_argument_parameters["action"] = "store"
reqparse_argument_parameters["type"] = type_map_ma_to_reqparse.get(value_type, str)
if hasattr(value, "required"):
reqparse_argument_parameters["required"] = value.required
if hasattr(value, "metadata") and "description" in value.metadata:
reqparse_argument_parameters["help"] = value.metadata["description"]
return reqparse_argument_parameters
示例7: _deserialize
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def _deserialize(
self,
value: Any,
attr: Optional[str],
data: Optional[Mapping[str, Any]],
**kwargs,
) -> SyncFilesItem:
if isinstance(value, dict):
try:
if not isinstance(value["src"], str):
raise ValidationError("Field `src` should have type str.")
if not isinstance(value["dest"], str):
raise ValidationError("Field `dest` should have type str.")
file_to_sync = SyncFilesItem(src=value["src"], dest=value["dest"])
except KeyError as e:
raise ValidationError(e.__repr__())
elif isinstance(value, str):
file_to_sync = SyncFilesItem(src=value, dest=value)
else:
raise ValidationError(f"'dict' or 'str' required, got {type(value)!r}.")
return file_to_sync
示例8: field2choices
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def field2choices(field):
"""Return the set of valid choices for a Field
or ``None`` if no choices are specified.
:param Field field: A marshmallow field.
:rtype: set
"""
comparable = {
validator.comparable for validator in field.validators
if hasattr(validator, 'comparable')
}
if comparable:
return comparable
choices = [
OrderedSet(validator.choices) for validator in field.validators
if hasattr(validator, 'choices')
]
if choices:
return functools.reduce(operator.and_, choices)
示例9: handle_error
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def handle_error(self,
error: MarshmallowValidationError,
data: Any, # skipcq: PYL-W0613 (unused arg)
**kwargs
) -> None:
"""
Customize the error messages for required/not-null validators with
dynamically generated field names. This is definitely a little hacky (it
mutates state, uses hardcoded strings), but unsure how better to do it
"""
required_messages = {'Missing data for required field.',
'Field may not be null.'}
for field_name in error.normalized_messages():
for i, msg in enumerate(error.messages[field_name]):
if isinstance(msg, _LazyString):
msg = str(msg)
if msg in required_messages:
label = title_case(field_name)
error.messages[field_name][i] = f'{label} is required.'
示例10: test_use_type_mapping_from_base_schema
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [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)
示例11: __init__
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def __init__(self):
self.encoders: Dict[type, Callable] = {}
self.decoders: Dict[type, Callable] = {}
self.mm_fields: Dict[type, MarshmallowField] = {}
# self._json_module = json
# TODO: #180
# @property
# def json_module(self):
# return self._json_module
#
# @json_module.setter
# def json_module(self, value):
# warnings.warn(f"Now using {value.__name__} module to handle JSON. "
# f"{self._disable_msg}")
# self._json_module = value
示例12: serialize
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def serialize(self, attr_name, field_symbol,
assignment_template, field_obj):
# type: (str, str, str, fields.Field) -> IndentedString
"""Generates the code to pull a field off of an object into the result.
:param attr_name: The name of the attribute being accessed/
:param field_symbol: The symbol to use when accessing the field. Should
be generated via field_symbol_name.
:param assignment_template: A string template to use when generating
code. The assignment template is passed into the serializer and
has a single possitional placeholder for string formatting. An
example of a value that may be passed into assignment_template is:
`res['some_field'] = {0}`
:param field_obj: The instance of the Marshmallow field being
serialized.
:return: The code to pull a field off of the object passed in.
"""
pass # pragma: no cover
示例13: inline
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def inline(self, field, context):
# type: (fields.Field, JitContext) -> Optional[str]
"""Generates a template for inlining boolean serialization.
For example, generates:
(
(value in __some_field_truthy) or
(False if value in __some_field_falsy else bool(value))
)
This is somewhat fragile but it tracks what Marshmallow does.
"""
if is_overridden(field._serialize, fields.Boolean._serialize):
return None
truthy_symbol = '__{0}_truthy'.format(field.name)
falsy_symbol = '__{0}_falsy'.format(field.name)
context.namespace[truthy_symbol] = field.truthy
context.namespace[falsy_symbol] = field.falsy
result = ('(({0} in ' + truthy_symbol +
') or (False if {0} in ' + falsy_symbol +
' else dict()["error"]))')
return result + ' if {0} is not None else None'
示例14: test_unknown_typed_field_throws_valueerror
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def test_unknown_typed_field_throws_valueerror():
class Invalid(fields.Field):
def _serialize(self, value, attr, obj):
return value
class UserSchema(Schema):
favourite_colour = Invalid()
schema = UserSchema()
json_schema = JSONSchema()
with pytest.raises(UnsupportedValueError):
validate_and_dump(json_schema.dump(schema))
示例15: test_field_subclass
# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Field [as 别名]
def test_field_subclass():
"""JSON schema generation should not fail on sublcass marshmallow field."""
class CustomField(fields.Field):
pass
class TestSchema(Schema):
myfield = CustomField()
schema = TestSchema()
with pytest.raises(UnsupportedValueError):
_ = validate_and_dump(schema)