本文整理汇总了Python中marshmallow.missing方法的典型用法代码示例。如果您正苦于以下问题:Python marshmallow.missing方法的具体用法?Python marshmallow.missing怎么用?Python marshmallow.missing使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshmallow
的用法示例。
在下文中一共展示了marshmallow.missing方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _func2method
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def _func2method(func: typing.Callable, method_name: str) -> ParserMethod:
def method(
self: "Env", name: str, default: typing.Any = ma.missing, subcast: typing.Type = None, **kwargs
):
if self._sealed:
raise EnvSealedError("Env has already been sealed. New values cannot be parsed.")
parsed_key, raw_value, proxied_key = self._get_from_environ(name, default)
if raw_value is ma.missing:
raise EnvError('Environment variable "{}" not set'.format(proxied_key or parsed_key))
value = func(raw_value, **kwargs)
self._fields[parsed_key] = ma.fields.Field(**kwargs)
self._values[parsed_key] = value
return value
method.__name__ = method_name
return method
# From webargs
示例2: _preprocess_typehint
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def _preprocess_typehint(self, typehint, kwargs, field_name, target):
# while this seems contradictory to this converter, we need to
# ignore attrs specific actions when a container type, e.g. a List[T],
# contains a non-attrs manufactured type because this is recursively
# called during schema generation.
# however those types will still require an entry in the registry
# is handled outside this converter
if not _is_attrs(target):
return
attr = _get_attr_from_attrs(target.__attrs_attrs__, field_name)
if attr.default != NOTHING:
# default to optional even if the typehint isn't
# but don't override the user saying otherwise
kwargs.setdefault("required", False)
kwargs.setdefault("missing", missing)
示例3: get_field
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def get_field(self, view):
"""Construct the marshmallow field for deserializing filter values.
This takes the field from the deserializer, then creates a copy with
the desired semantics around missing values.
:param view: The view with the model we wish to filter for.
:type view: :py:class:`ModelView`
"""
base_field = view.deserializer.fields[self._column_name]
try:
field = self._fields[base_field]
except KeyError:
# We don't want the default value handling on the original field,
# as that's only relevant for object deserialization.
field = copy.deepcopy(base_field)
field.required = self._required
field.missing = self._missing
self._fields[base_field] = field
return field
示例4: _io_validate_data_proxy
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def _io_validate_data_proxy(schema, data_proxy, partial=None):
errors = {}
for name, field in schema.fields.items():
if partial and name not in partial:
continue
value = data_proxy.get(name)
if value is ma.missing:
continue
try:
if field.io_validate_recursive:
field.io_validate_recursive(field, value)
if field.io_validate:
_run_validators(field.io_validate, field, value)
except ma.ValidationError as exc:
errors[name] = exc.messages
if errors:
raise ma.ValidationError(errors)
示例5: _to_mongo_update
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def _to_mongo_update(self):
mongo_data = {}
set_data = {}
unset_data = []
for name in self.get_modified_fields():
field = self._fields[name]
name = field.attribute or name
val = field.serialize_to_mongo(self._data[name])
if val is ma.missing:
unset_data.append(name)
else:
set_data[name] = val
if set_data:
mongo_data['$set'] = set_data
if unset_data:
mongo_data['$unset'] = {k: "" for k in unset_data}
return mongo_data or None
示例6: schema_from_umongo_get_attribute
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def schema_from_umongo_get_attribute(self, obj, attr, default):
"""
Overwrite default `Schema.get_attribute` method by this one to access
umongo missing fields instead of returning `None`.
example::
class MySchema(marshsmallow.Schema):
get_attribute = schema_from_umongo_get_attribute
# Define the rest of your schema
...
"""
ret = ma.Schema.get_attribute(self, obj, attr, default)
if ret is None and ret is not default and attr in obj.schema.fields:
raw_ret = obj._data.get(attr)
return default if raw_ret is ma.missing else raw_ret
return ret
示例7: test_equality
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def test_equality(self):
class MySchema(Schema):
a = fields.IntField()
b = fields.IntField(attribute='in_mongo_b')
MyDataProxy = data_proxy_factory('My', MySchema())
d1 = MyDataProxy()
d1.load({'a': 1, 'b': 2})
assert d1 == {'a': 1, 'in_mongo_b': 2}
d2 = MyDataProxy()
d2.load({'a': 1, 'b': 2})
assert d1 == d2
assert d1 != None # noqa: E711 (None comparison)
assert d1 != ma.missing
assert None != d1 # noqa: E711 (None comparison)
assert ma.missing != d1
示例8: test_set_to_missing_fields
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def test_set_to_missing_fields(self):
class MySchema(Schema):
a = fields.IntField()
b = fields.IntField(attribute='in_mongo_b')
MyDataProxy = data_proxy_factory('My', MySchema())
d = MyDataProxy(data={'a': 1})
assert d.get('b') is ma.missing
assert d._data['in_mongo_b'] is ma.missing
d.set('b', 2)
assert d.get('b') == 2
d.delete('b')
# Can do it two time in a row without error
d.delete('b')
assert d._data['in_mongo_b'] is ma.missing
示例9: test_equality
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def test_equality(self):
@self.instance.register
class MyChildEmbeddedDocument(EmbeddedDocument):
num = fields.IntField()
@self.instance.register
class MyParentEmbeddedDocument(EmbeddedDocument):
embedded = fields.EmbeddedField(MyChildEmbeddedDocument)
emb_1 = MyParentEmbeddedDocument(embedded={'num': 1})
emb_2 = MyParentEmbeddedDocument(embedded={'num': 1})
emb_3 = MyParentEmbeddedDocument(embedded={})
emb_4 = MyParentEmbeddedDocument()
assert emb_1 == emb_2
assert emb_1 != emb_3
assert emb_1 != emb_4
assert emb_1 != None # noqa: E711 (None comparison)
assert emb_1 != ma.missing
assert None != emb_1 # noqa: E711 (None comparison)
assert ma.missing != emb_1
示例10: test_dump_only
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def test_dump_only(self):
@self.instance.register
class Doc(Document):
dl = fields.IntField()
do = fields.IntField(dump_only=True)
lo = fields.IntField(load_only=True)
nope = fields.IntField(dump_only=True, load_only=True)
with pytest.raises(ma.ValidationError):
Doc(do=1)
with pytest.raises(ma.ValidationError):
Doc(nope=1)
assert Doc(dl=1, lo=2).dump() == {'dl': 1}
with pytest.raises(ma.ValidationError) as excinfo:
Doc(nope=ma.missing, do=ma.missing)
assert excinfo.value.messages == {'nope': ['Unknown field.'], 'do': ['Unknown field.']}
示例11: _from_python_type
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [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
示例12: convert_all
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def convert_all(
self,
target: type,
ignore: AbstractSet[str] = frozenset([]), # noqa
configs: NamedConfigs = None,
) -> GeneratedFields:
configs = configs if configs is not None else {}
for k, default in self._get_field_defaults(target).items():
configs[k] = {"missing": default, **configs.get(k, {})}
return {
k: self.convert(v, configs.get(k, {}), field_name=k, target=target)
for k, v in self._get_type_hints(target, ignore)
}
示例13: _field_from_typehint
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def _field_from_typehint(
self, typehint, kwargs=None, *, field_name: str = None, target: type = None
):
# need that immutable dict in the stdlib pls
kwargs = kwargs if kwargs is not None else {}
self._preprocess_typehint(typehint, kwargs, field_name, target)
# sane defaults
allow_none = False
required = True
missing = marshmallow.missing
if _is_optional(typehint):
allow_none = True
required = False
missing = None
typehint = _extract_optional(typehint)
# set this after optional check
subtypes = getattr(typehint, "__args__", ())
if subtypes != ():
typehint = _get_base(typehint)
kwargs.setdefault("allow_none", allow_none)
kwargs.setdefault("required", required)
kwargs.setdefault("missing", missing)
self._postprocess_typehint(typehint, kwargs, field_name, target)
field_constructor = self.registry.get(typehint)
return field_constructor(self, subtypes, kwargs)
示例14: test_defaults_missing
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def test_defaults_missing(registry_):
class FieldDefaultConverter(BaseConverter):
def _get_field_defaults(self, item):
return {"points": [1.0, 2.0]}
converter = FieldDefaultConverter(registry=registry_)
generated_fields = converter.convert_all(SomeType)
assert generated_fields["id"].missing == missing
assert generated_fields["name"].missing is None
assert generated_fields["points"].missing == [1.0, 2.0]
示例15: test_override_missing
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import missing [as 别名]
def test_override_missing(registry_):
converter = BaseConverter(registry=registry_)
named_options = {"points": {"missing": list}, "name": {"missing": "a"}}
generated_fields = converter.convert_all(SomeType, configs=named_options)
assert generated_fields["id"].missing == missing
assert generated_fields["name"].missing == "a"
assert generated_fields["points"].missing == list