fields.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. # -*- coding: utf-8 -*-
  2. """Field classes for various types of data."""
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import copy
  6. import datetime as dt
  7. import numbers
  8. import uuid
  9. import decimal
  10. import math
  11. from marshmallow import validate, utils, class_registry
  12. from marshmallow.base import FieldABC, SchemaABC
  13. from marshmallow.utils import is_collection, missing as missing_, resolve_field_instance
  14. from marshmallow.compat import basestring, Mapping as _Mapping, iteritems
  15. from marshmallow.exceptions import (
  16. ValidationError,
  17. StringNotCollectionError,
  18. FieldInstanceResolutionError,
  19. )
  20. from marshmallow.validate import Validator, Length
  21. __all__ = [
  22. 'Field',
  23. 'Raw',
  24. 'Nested',
  25. 'Mapping',
  26. 'Dict',
  27. 'List',
  28. 'Tuple',
  29. 'String',
  30. 'UUID',
  31. 'Number',
  32. 'Integer',
  33. 'Decimal',
  34. 'Boolean',
  35. 'Float',
  36. 'DateTime',
  37. 'LocalDateTime',
  38. 'Time',
  39. 'Date',
  40. 'TimeDelta',
  41. 'Url',
  42. 'URL',
  43. 'Email',
  44. 'Method',
  45. 'Function',
  46. 'Str',
  47. 'Bool',
  48. 'Int',
  49. 'Constant',
  50. ]
  51. MISSING_ERROR_MESSAGE = (
  52. 'ValidationError raised by `{class_name}`, but error key `{key}` does '
  53. 'not exist in the `error_messages` dictionary.'
  54. )
  55. class Field(FieldABC):
  56. """Basic field from which other fields should extend. It applies no
  57. formatting by default, and should only be used in cases where
  58. data does not need to be formatted before being serialized or deserialized.
  59. On error, the name of the field will be returned.
  60. :param default: If set, this value will be used during serialization if the input value
  61. is missing. If not set, the field will be excluded from the serialized output if the
  62. input value is missing. May be a value or a callable.
  63. :param str attribute: The name of the attribute to get the value from when serializing.
  64. If `None`, assumes the attribute has the same name as the field.
  65. :param str data_key: The name of the key to get the value from when deserializing.
  66. If `None`, assumes the key has the same name as the field.
  67. :param callable validate: Validator or collection of validators that are called
  68. during deserialization. Validator takes a field's input value as
  69. its only parameter and returns a boolean.
  70. If it returns `False`, an :exc:`ValidationError` is raised.
  71. :param required: Raise a :exc:`ValidationError` if the field value
  72. is not supplied during deserialization.
  73. :param allow_none: Set this to `True` if `None` should be considered a valid value during
  74. validation/deserialization. If ``missing=None`` and ``allow_none`` is unset,
  75. will default to ``True``. Otherwise, the default is ``False``.
  76. :param bool load_only: If `True` skip this field during serialization, otherwise
  77. its value will be present in the serialized data.
  78. :param bool dump_only: If `True` skip this field during deserialization, otherwise
  79. its value will be present in the deserialized object. In the context of an
  80. HTTP API, this effectively marks the field as "read-only".
  81. :param missing: Default deserialization value for the field if the field is not
  82. found in the input data. May be a value or a callable.
  83. :param dict error_messages: Overrides for `Field.default_error_messages`.
  84. :param metadata: Extra arguments to be stored as metadata.
  85. .. versionchanged:: 2.0.0
  86. Removed `error` parameter. Use ``error_messages`` instead.
  87. .. versionchanged:: 2.0.0
  88. Added `allow_none` parameter, which makes validation/deserialization of `None`
  89. consistent across fields.
  90. .. versionchanged:: 2.0.0
  91. Added `load_only` and `dump_only` parameters, which allow field skipping
  92. during the (de)serialization process.
  93. .. versionchanged:: 2.0.0
  94. Added `missing` parameter, which indicates the value for a field if the field
  95. is not found during deserialization.
  96. .. versionchanged:: 2.0.0
  97. ``default`` value is only used if explicitly set. Otherwise, missing values
  98. inputs are excluded from serialized output.
  99. .. versionchanged:: 3.0.0b8
  100. Add ``data_key`` parameter for the specifying the key in the input and
  101. output data. This parameter replaced both ``load_from`` and ``dump_to``.
  102. """
  103. # Some fields, such as Method fields and Function fields, are not expected
  104. # to exist as attributes on the objects to serialize. Set this to False
  105. # for those fields
  106. _CHECK_ATTRIBUTE = True
  107. _creation_index = 0 # Used for sorting
  108. #: Default error messages for various kinds of errors. The keys in this dictionary
  109. #: are passed to `Field.fail`. The values are error messages passed to
  110. #: :exc:`marshmallow.exceptions.ValidationError`.
  111. default_error_messages = {
  112. 'required': 'Missing data for required field.',
  113. 'null': 'Field may not be null.',
  114. 'validator_failed': 'Invalid value.',
  115. }
  116. def __init__(
  117. self,
  118. default=missing_,
  119. attribute=None,
  120. data_key=None,
  121. error=None,
  122. validate=None,
  123. required=False,
  124. allow_none=None,
  125. load_only=False,
  126. dump_only=False,
  127. missing=missing_,
  128. error_messages=None,
  129. **metadata
  130. ):
  131. self.default = default
  132. self.attribute = attribute
  133. self.data_key = data_key
  134. self.validate = validate
  135. if utils.is_iterable_but_not_string(validate):
  136. if not utils.is_generator(validate):
  137. self.validators = validate
  138. else:
  139. self.validators = list(validate)
  140. elif callable(validate):
  141. self.validators = [validate]
  142. elif validate is None:
  143. self.validators = []
  144. else:
  145. raise ValueError(
  146. "The 'validate' parameter must be a callable "
  147. 'or a collection of callables.',
  148. )
  149. # If missing=None, None should be considered valid by default
  150. if allow_none is None:
  151. if missing is None:
  152. self.allow_none = True
  153. else:
  154. self.allow_none = False
  155. else:
  156. self.allow_none = allow_none
  157. self.load_only = load_only
  158. self.dump_only = dump_only
  159. if required is True and missing is not missing_:
  160. raise ValueError("'missing' must not be set for required fields.")
  161. self.required = required
  162. self.missing = missing
  163. self.metadata = metadata
  164. self._creation_index = Field._creation_index
  165. Field._creation_index += 1
  166. # Collect default error message from self and parent classes
  167. messages = {}
  168. for cls in reversed(self.__class__.__mro__):
  169. messages.update(getattr(cls, 'default_error_messages', {}))
  170. messages.update(error_messages or {})
  171. self.error_messages = messages
  172. def __repr__(self):
  173. return (
  174. '<fields.{ClassName}(default={self.default!r}, '
  175. 'attribute={self.attribute!r}, '
  176. 'validate={self.validate}, required={self.required}, '
  177. 'load_only={self.load_only}, dump_only={self.dump_only}, '
  178. 'missing={self.missing}, allow_none={self.allow_none}, '
  179. 'error_messages={self.error_messages})>'.format(
  180. ClassName=self.__class__.__name__, self=self,
  181. )
  182. )
  183. def get_value(self, obj, attr, accessor=None, default=missing_):
  184. """Return the value for a given key from an object.
  185. :param object obj: The object to get the value from
  186. :param str attr: The attribute/key in `obj` to get the value from.
  187. :param callable accessor: A callable used to retrieve the value of `attr` from
  188. the object `obj`. Defaults to `marshmallow.utils.get_value`.
  189. """
  190. # NOTE: Use getattr instead of direct attribute access here so that
  191. # subclasses aren't required to define `attribute` member
  192. attribute = getattr(self, 'attribute', None)
  193. accessor_func = accessor or utils.get_value
  194. check_key = attr if attribute is None else attribute
  195. return accessor_func(obj, check_key, default)
  196. def _validate(self, value):
  197. """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
  198. does not succeed.
  199. """
  200. errors = []
  201. kwargs = {}
  202. for validator in self.validators:
  203. try:
  204. r = validator(value)
  205. if not isinstance(validator, Validator) and r is False:
  206. self.fail('validator_failed')
  207. except ValidationError as err:
  208. kwargs.update(err.kwargs)
  209. if isinstance(err.messages, dict):
  210. errors.append(err.messages)
  211. else:
  212. errors.extend(err.messages)
  213. if errors:
  214. raise ValidationError(errors, **kwargs)
  215. # Hat tip to django-rest-framework.
  216. def fail(self, key, **kwargs):
  217. """A helper method that simply raises a `ValidationError`.
  218. """
  219. try:
  220. msg = self.error_messages[key]
  221. except KeyError:
  222. class_name = self.__class__.__name__
  223. msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
  224. raise AssertionError(msg)
  225. if isinstance(msg, basestring):
  226. msg = msg.format(**kwargs)
  227. raise ValidationError(msg)
  228. def _validate_missing(self, value):
  229. """Validate missing values. Raise a :exc:`ValidationError` if
  230. `value` should be considered missing.
  231. """
  232. if value is missing_:
  233. if hasattr(self, 'required') and self.required:
  234. self.fail('required')
  235. if value is None:
  236. if hasattr(self, 'allow_none') and self.allow_none is not True:
  237. self.fail('null')
  238. def serialize(self, attr, obj, accessor=None, **kwargs):
  239. """Pulls the value for the given key from the object, applies the
  240. field's formatting and returns the result.
  241. :param str attr: The attribute or key to get from the object.
  242. :param str obj: The object to pull the key from.
  243. :param callable accessor: Function used to pull values from ``obj``.
  244. :param dict kwargs': Field-specific keyword arguments.
  245. :raise ValidationError: In case of formatting problem
  246. """
  247. if self._CHECK_ATTRIBUTE:
  248. value = self.get_value(obj, attr, accessor=accessor)
  249. if value is missing_ and hasattr(self, 'default'):
  250. default = self.default
  251. value = default() if callable(default) else default
  252. if value is missing_:
  253. return value
  254. else:
  255. value = None
  256. return self._serialize(value, attr, obj, **kwargs)
  257. def deserialize(self, value, attr=None, data=None, **kwargs):
  258. """Deserialize ``value``.
  259. :param value: The value to be deserialized.
  260. :param str attr: The attribute/key in `data` to be deserialized.
  261. :param dict data: The raw input data passed to the `Schema.load`.
  262. :param dict kwargs': Field-specific keyword arguments.
  263. :raise ValidationError: If an invalid value is passed or if a required value
  264. is missing.
  265. """
  266. # Validate required fields, deserialize, then validate
  267. # deserialized value
  268. self._validate_missing(value)
  269. if value is missing_:
  270. _miss = self.missing
  271. return _miss() if callable(_miss) else _miss
  272. if getattr(self, 'allow_none', False) is True and value is None:
  273. return None
  274. output = self._deserialize(value, attr, data, **kwargs)
  275. self._validate(output)
  276. return output
  277. # Methods for concrete classes to override.
  278. def _bind_to_schema(self, field_name, schema):
  279. """Update field with values from its parent schema. Called by
  280. :meth:`_bind_field<marshmallow.Schema._bind_field>`.
  281. :param str field_name: Field name set in schema.
  282. :param Schema schema: Parent schema.
  283. """
  284. self.parent = self.parent or schema
  285. self.name = self.name or field_name
  286. def _serialize(self, value, attr, obj, **kwargs):
  287. """Serializes ``value`` to a basic Python datatype. Noop by default.
  288. Concrete :class:`Field` classes should implement this method.
  289. Example: ::
  290. class TitleCase(Field):
  291. def _serialize(self, value, attr, obj, **kwargs):
  292. if not value:
  293. return ''
  294. return unicode(value).title()
  295. :param value: The value to be serialized.
  296. :param str attr: The attribute or key on the object to be serialized.
  297. :param object obj: The object the value was pulled from.
  298. :param dict kwargs': Field-specific keyword arguments.
  299. :raise ValidationError: In case of formatting or validation failure.
  300. :return: The serialized value
  301. """
  302. return value
  303. def _deserialize(self, value, attr, data, **kwargs):
  304. """Deserialize value. Concrete :class:`Field` classes should implement this method.
  305. :param value: The value to be deserialized.
  306. :param str attr: The attribute/key in `data` to be deserialized.
  307. :param dict data: The raw input data passed to the `Schema.load`.
  308. :param dict kwargs': Field-specific keyword arguments.
  309. :raise ValidationError: In case of formatting or validation failure.
  310. :return: The deserialized value.
  311. .. versionchanged:: 3.0.0
  312. Add ``**kwargs`` parameters
  313. .. versionchanged:: 2.0.0
  314. Added ``attr`` and ``data`` parameters.
  315. """
  316. return value
  317. # Properties
  318. @property
  319. def context(self):
  320. """The context dictionary for the parent :class:`Schema`."""
  321. return self.parent.context
  322. @property
  323. def root(self):
  324. """Reference to the `Schema` that this field belongs to even if it is buried in a `List`.
  325. Return `None` for unbound fields.
  326. """
  327. ret = self
  328. while hasattr(ret, 'parent') and ret.parent:
  329. ret = ret.parent
  330. return ret if isinstance(ret, SchemaABC) else None
  331. class Raw(Field):
  332. """Field that applies no formatting or validation."""
  333. pass
  334. class Nested(Field):
  335. """Allows you to nest a :class:`Schema <marshmallow.Schema>`
  336. inside a field.
  337. Examples: ::
  338. user = fields.Nested(UserSchema)
  339. user2 = fields.Nested('UserSchema') # Equivalent to above
  340. collaborators = fields.Nested(UserSchema, many=True, only=('id',))
  341. parent = fields.Nested('self')
  342. When passing a `Schema <marshmallow.Schema>` instance as the first argument,
  343. the instance's ``exclude``, ``only``, and ``many`` attributes will be respected.
  344. Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`,
  345. you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument.
  346. ::
  347. # Yes
  348. author = fields.Nested(UserSchema, only=('id', 'name'))
  349. # No
  350. author = fields.Nested(UserSchema(), only=('id', 'name'))
  351. :param Schema nested: The Schema class or class name (string)
  352. to nest, or ``"self"`` to nest the :class:`Schema` within itself.
  353. :param tuple exclude: A list or tuple of fields to exclude.
  354. :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled.
  355. This parameter takes precedence over ``exclude``.
  356. :param bool many: Whether the field is a collection of objects.
  357. :param unknown: Whether to exclude, include, or raise an error for unknown
  358. fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
  359. :param kwargs: The same keyword arguments that :class:`Field` receives.
  360. """
  361. default_error_messages = {'type': 'Invalid type.'}
  362. def __init__(self, nested, default=missing_, exclude=tuple(), only=None, **kwargs):
  363. # Raise error if only or exclude is passed as string, not list of strings
  364. if only is not None and not is_collection(only):
  365. raise StringNotCollectionError('"only" should be a list of strings.')
  366. if exclude is not None and not is_collection(exclude):
  367. raise StringNotCollectionError('"exclude" should be a list of strings.')
  368. self.nested = nested
  369. self.only = only
  370. self.exclude = exclude
  371. self.many = kwargs.get('many', False)
  372. self.unknown = kwargs.get('unknown')
  373. self.__schema = None # Cached Schema instance
  374. super(Nested, self).__init__(default=default, **kwargs)
  375. @property
  376. def schema(self):
  377. """The nested Schema object.
  378. .. versionchanged:: 1.0.0
  379. Renamed from `serializer` to `schema`
  380. """
  381. if not self.__schema:
  382. # Inherit context from parent.
  383. context = getattr(self.parent, 'context', {})
  384. if isinstance(self.nested, SchemaABC):
  385. self.__schema = self.nested
  386. self.__schema.context.update(context)
  387. else:
  388. if isinstance(self.nested, type) and issubclass(self.nested, SchemaABC):
  389. schema_class = self.nested
  390. elif not isinstance(self.nested, basestring):
  391. raise ValueError(
  392. 'Nested fields must be passed a '
  393. 'Schema, not {0}.'.format(self.nested.__class__),
  394. )
  395. elif self.nested == 'self':
  396. schema_class = self.parent.__class__
  397. else:
  398. schema_class = class_registry.get_class(self.nested)
  399. self.__schema = schema_class(
  400. many=self.many,
  401. only=self.only,
  402. exclude=self.exclude,
  403. context=context,
  404. load_only=self._nested_normalized_option('load_only'),
  405. dump_only=self._nested_normalized_option('dump_only'),
  406. )
  407. self.__schema.ordered = getattr(self.parent, 'ordered', False)
  408. return self.__schema
  409. def _nested_normalized_option(self, option_name):
  410. nested_field = '%s.' % self.name
  411. return [
  412. field.split(nested_field, 1)[1]
  413. for field in getattr(self.root, option_name, set())
  414. if field.startswith(nested_field)
  415. ]
  416. def _serialize(self, nested_obj, attr, obj, **kwargs):
  417. # Load up the schema first. This allows a RegistryError to be raised
  418. # if an invalid schema name was passed
  419. schema = self.schema
  420. if nested_obj is None:
  421. return None
  422. try:
  423. return schema.dump(nested_obj, many=self.many)
  424. except ValidationError as exc:
  425. raise ValidationError(exc.messages, valid_data=exc.valid_data)
  426. def _test_collection(self, value):
  427. if self.many and not utils.is_collection(value):
  428. self.fail('type', input=value, type=value.__class__.__name__)
  429. def _load(self, value, data, partial=None):
  430. try:
  431. valid_data = self.schema.load(value, unknown=self.unknown, partial=partial)
  432. except ValidationError as exc:
  433. raise ValidationError(exc.messages, valid_data=exc.valid_data)
  434. return valid_data
  435. def _deserialize(self, value, attr, data, partial=None, **kwargs):
  436. """Same as :meth:`Field._deserialize` with additional ``partial`` argument.
  437. :param bool|tuple partial: For nested schemas, the ``partial``
  438. parameter passed to `Schema.load`.
  439. .. versionchanged:: 3.0.0
  440. Add ``partial`` parameter
  441. """
  442. self._test_collection(value)
  443. return self._load(value, data, partial=partial)
  444. class Pluck(Nested):
  445. """Allows you to replace nested data with one of the data's fields.
  446. Examples: ::
  447. user = fields.Pluck(UserSchema, 'name')
  448. collaborators = fields.Pluck(UserSchema, 'id', many=True)
  449. parent = fields.Pluck('self', 'name')
  450. :param Schema nested: The Schema class or class name (string)
  451. to nest, or ``"self"`` to nest the :class:`Schema` within itself.
  452. :param str field_name:
  453. :param kwargs: The same keyword arguments that :class:`Nested` receives.
  454. """
  455. def __init__(self, nested, field_name, **kwargs):
  456. super(Pluck, self).__init__(nested, only=(field_name,), **kwargs)
  457. self.field_name = field_name
  458. @property
  459. def _field_data_key(self):
  460. only_field = self.schema.fields[self.field_name]
  461. return only_field.data_key or self.field_name
  462. def _serialize(self, nested_obj, attr, obj, **kwargs):
  463. ret = super(Pluck, self)._serialize(nested_obj, attr, obj, **kwargs)
  464. if ret is None:
  465. return None
  466. if self.many:
  467. return utils.pluck(ret, key=self._field_data_key)
  468. return ret[self._field_data_key]
  469. def _deserialize(self, value, attr, data, partial=None, **kwargs):
  470. self._test_collection(value)
  471. if self.many:
  472. value = [{self._field_data_key: v} for v in value]
  473. else:
  474. value = {self._field_data_key: value}
  475. return self._load(value, data, partial=partial)
  476. class List(Field):
  477. """A list field, composed with another `Field` class or
  478. instance.
  479. Example: ::
  480. numbers = fields.List(fields.Float())
  481. :param Field cls_or_instance: A field class or instance.
  482. :param bool default: Default value for serialization.
  483. :param kwargs: The same keyword arguments that :class:`Field` receives.
  484. .. versionchanged:: 2.0.0
  485. The ``allow_none`` parameter now applies to deserialization and
  486. has the same semantics as the other fields.
  487. """
  488. default_error_messages = {'invalid': 'Not a valid list.'}
  489. def __init__(self, cls_or_instance, **kwargs):
  490. super(List, self).__init__(**kwargs)
  491. try:
  492. self.container = resolve_field_instance(cls_or_instance)
  493. except FieldInstanceResolutionError:
  494. raise ValueError(
  495. 'The list elements must be a subclass or instance of '
  496. 'marshmallow.base.FieldABC.',
  497. )
  498. def get_value(self, obj, attr, accessor=None):
  499. """Return the value for a given key from an object."""
  500. value = super(List, self).get_value(obj, attr, accessor=accessor)
  501. if self.container.attribute:
  502. if utils.is_collection(value):
  503. return [
  504. self.container.get_value(each, self.container.attribute)
  505. for each in value
  506. ]
  507. return self.container.get_value(value, self.container.attribute)
  508. return value
  509. def _bind_to_schema(self, field_name, schema):
  510. super(List, self)._bind_to_schema(field_name, schema)
  511. self.container = copy.deepcopy(self.container)
  512. self.container.parent = self
  513. self.container.name = field_name
  514. def _serialize(self, value, attr, obj, **kwargs):
  515. if value is None:
  516. return None
  517. if utils.is_collection(value):
  518. return [
  519. self.container._serialize(each, attr, obj, **kwargs) for each in value
  520. ]
  521. return [self.container._serialize(value, attr, obj, **kwargs)]
  522. def _deserialize(self, value, attr, data, **kwargs):
  523. if not utils.is_collection(value):
  524. self.fail('invalid')
  525. result = []
  526. errors = {}
  527. for idx, each in enumerate(value):
  528. try:
  529. result.append(self.container.deserialize(each))
  530. except ValidationError as error:
  531. if error.valid_data is not None:
  532. result.append(error.valid_data)
  533. errors.update({idx: error.messages})
  534. if errors:
  535. raise ValidationError(errors, valid_data=result)
  536. return result
  537. class Tuple(Field):
  538. """A tuple field, composed of a fixed number of other `Field` classes or
  539. instances
  540. Example: ::
  541. row = Tuple((fields.String(), fields.Integer(), fields.Float()))
  542. .. note::
  543. Because of the structured nature of `collections.namedtuple` and
  544. `typing.NamedTuple`, using a Schema within a Nested field for them is
  545. more appropriate than using a `Tuple` field.
  546. :param Iterable[Field] tuple_fields: An iterable of field classes or
  547. instances.
  548. :param kwargs: The same keyword arguments that :class:`Field` receives.
  549. .. versionadded:: 3.0.0rc4
  550. """
  551. default_error_messages = {'invalid': 'Not a valid tuple.'}
  552. def __init__(self, tuple_fields, *args, **kwargs):
  553. super(Tuple, self).__init__(*args, **kwargs)
  554. if not utils.is_collection(tuple_fields):
  555. raise ValueError(
  556. 'tuple_fields must be an iterable of Field classes or ' 'instances.',
  557. )
  558. try:
  559. self.tuple_fields = [
  560. resolve_field_instance(cls_or_instance)
  561. for cls_or_instance in tuple_fields
  562. ]
  563. except FieldInstanceResolutionError:
  564. raise ValueError(
  565. 'Elements of "tuple_fields" must be subclasses or '
  566. 'instances of marshmallow.base.FieldABC.',
  567. )
  568. self.validate_length = Length(equal=len(self.tuple_fields))
  569. def _bind_to_schema(self, field_name, schema):
  570. super(Tuple, self)._bind_to_schema(field_name, schema)
  571. new_tuple_fields = []
  572. for container in self.tuple_fields:
  573. new_container = copy.deepcopy(container)
  574. new_container.parent = self
  575. new_container.name = field_name
  576. new_tuple_fields.append(new_container)
  577. self.tuple_fields = new_tuple_fields
  578. def get_value(self, obj, attr, accessor=None):
  579. """Return the value for a given key from an object."""
  580. value = super(Tuple, self).get_value(obj, attr, accessor=accessor)
  581. if any(container.attribute for container in self.tuple_fields):
  582. if not utils.is_collection(value):
  583. self.fail('invalid')
  584. result = []
  585. for container, each in zip(self.tuple_fields, value):
  586. if container.attribute is None:
  587. result.append(each)
  588. else:
  589. result.append(container.get_value(each, container.attribute))
  590. return tuple(result)
  591. return value
  592. def _serialize(self, value, attr, obj, **kwargs):
  593. if value is None:
  594. return None
  595. return tuple(
  596. container._serialize(each, attr, obj, **kwargs)
  597. for container, each in zip(self.tuple_fields, value)
  598. )
  599. def _deserialize(self, value, attr, data, **kwargs):
  600. if not utils.is_collection(value):
  601. self.fail('invalid')
  602. self.validate_length(value)
  603. result = []
  604. errors = {}
  605. for idx, (container, each) in enumerate(zip(self.tuple_fields, value)):
  606. try:
  607. result.append(container.deserialize(each))
  608. except ValidationError as error:
  609. if error.valid_data is not None:
  610. result.append(error.valid_data)
  611. errors.update({idx: error.messages})
  612. if errors:
  613. raise ValidationError(errors, valid_data=result)
  614. return tuple(result)
  615. class String(Field):
  616. """A string field.
  617. :param kwargs: The same keyword arguments that :class:`Field` receives.
  618. """
  619. default_error_messages = {
  620. 'invalid': 'Not a valid string.',
  621. 'invalid_utf8': 'Not a valid utf-8 string.',
  622. }
  623. def _serialize(self, value, attr, obj, **kwargs):
  624. if value is None:
  625. return None
  626. return utils.ensure_text_type(value)
  627. def _deserialize(self, value, attr, data, **kwargs):
  628. if not isinstance(value, basestring):
  629. self.fail('invalid')
  630. try:
  631. return utils.ensure_text_type(value)
  632. except UnicodeDecodeError:
  633. self.fail('invalid_utf8')
  634. class UUID(String):
  635. """A UUID field."""
  636. default_error_messages = {'invalid_uuid': 'Not a valid UUID.'}
  637. def _validated(self, value):
  638. """Format the value or raise a :exc:`ValidationError` if an error occurs."""
  639. if value is None:
  640. return None
  641. if isinstance(value, uuid.UUID):
  642. return value
  643. try:
  644. if isinstance(value, bytes) and len(value) == 16:
  645. return uuid.UUID(bytes=value)
  646. else:
  647. return uuid.UUID(value)
  648. except (ValueError, AttributeError, TypeError):
  649. self.fail('invalid_uuid')
  650. def _serialize(self, value, attr, obj, **kwargs):
  651. validated = str(self._validated(value)) if value is not None else None
  652. return super(String, self)._serialize(validated, attr, obj, **kwargs)
  653. def _deserialize(self, value, attr, data, **kwargs):
  654. return self._validated(value)
  655. class Number(Field):
  656. """Base class for number fields.
  657. :param bool as_string: If True, format the serialized value as a string.
  658. :param kwargs: The same keyword arguments that :class:`Field` receives.
  659. """
  660. num_type = float
  661. default_error_messages = {'invalid': 'Not a valid number.'}
  662. default_error_messages = {
  663. 'invalid': 'Not a valid number.',
  664. 'too_large': 'Number too large.',
  665. }
  666. def __init__(self, as_string=False, **kwargs):
  667. self.as_string = as_string
  668. super(Number, self).__init__(**kwargs)
  669. def _format_num(self, value):
  670. """Return the number value for value, given this field's `num_type`."""
  671. # (value is True or value is False) is ~5x faster than isinstance(value, bool)
  672. if value is True or value is False:
  673. raise TypeError('value must be a Number, not a boolean.')
  674. return self.num_type(value)
  675. def _validated(self, value):
  676. """Format the value or raise a :exc:`ValidationError` if an error occurs."""
  677. if value is None:
  678. return None
  679. try:
  680. return self._format_num(value)
  681. except (TypeError, ValueError):
  682. self.fail('invalid', input=value)
  683. except OverflowError:
  684. self.fail('too_large', input=value)
  685. def _to_string(self, value):
  686. return str(value)
  687. def _serialize(self, value, attr, obj, **kwargs):
  688. """Return a string if `self.as_string=True`, otherwise return this field's `num_type`."""
  689. ret = self._validated(value)
  690. return (
  691. self._to_string(ret)
  692. if (self.as_string and ret not in (None, missing_))
  693. else ret
  694. )
  695. def _deserialize(self, value, attr, data, **kwargs):
  696. return self._validated(value)
  697. class Integer(Number):
  698. """An integer field.
  699. :param kwargs: The same keyword arguments that :class:`Number` receives.
  700. """
  701. num_type = int
  702. default_error_messages = {'invalid': 'Not a valid integer.'}
  703. # override Number
  704. def __init__(self, strict=False, **kwargs):
  705. self.strict = strict
  706. super(Integer, self).__init__(**kwargs)
  707. # override Number
  708. def _format_num(self, value):
  709. if self.strict:
  710. if isinstance(value, numbers.Number) and isinstance(
  711. value, numbers.Integral,
  712. ):
  713. return super(Integer, self)._format_num(value)
  714. self.fail('invalid', input=value)
  715. return super(Integer, self)._format_num(value)
  716. class Float(Number):
  717. """
  718. A double as IEEE-754 double precision string.
  719. :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,
  720. even though they are illegal according to the JSON specification.
  721. :param bool as_string: If True, format the value as a string.
  722. :param kwargs: The same keyword arguments that :class:`Number` receives.
  723. """
  724. num_type = float
  725. default_error_messages = {
  726. 'special': 'Special numeric values (nan or infinity) are not permitted.',
  727. }
  728. def __init__(self, allow_nan=False, as_string=False, **kwargs):
  729. self.allow_nan = allow_nan
  730. super(Float, self).__init__(as_string=as_string, **kwargs)
  731. def _format_num(self, value):
  732. num = super(Float, self)._format_num(value)
  733. if self.allow_nan is False:
  734. if math.isnan(num) or num == float('inf') or num == float('-inf'):
  735. self.fail('special')
  736. return num
  737. class Decimal(Number):
  738. """A field that (de)serializes to the Python ``decimal.Decimal`` type.
  739. It's safe to use when dealing with money values, percentages, ratios
  740. or other numbers where precision is critical.
  741. .. warning::
  742. This field serializes to a `decimal.Decimal` object by default. If you need
  743. to render your data as JSON, keep in mind that the `json` module from the
  744. standard library does not encode `decimal.Decimal`. Therefore, you must use
  745. a JSON library that can handle decimals, such as `simplejson`, or serialize
  746. to a string by passing ``as_string=True``.
  747. .. warning::
  748. If a JSON `float` value is passed to this field for deserialization it will
  749. first be cast to its corresponding `string` value before being deserialized
  750. to a `decimal.Decimal` object. The default `__str__` implementation of the
  751. built-in Python `float` type may apply a destructive transformation upon
  752. its input data and therefore cannot be relied upon to preserve precision.
  753. To avoid this, you can instead pass a JSON `string` to be deserialized
  754. directly.
  755. :param int places: How many decimal places to quantize the value. If `None`, does
  756. not quantize the value.
  757. :param rounding: How to round the value during quantize, for example
  758. `decimal.ROUND_UP`. If None, uses the rounding value from
  759. the current thread's context.
  760. :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,
  761. even though they are illegal according to the JSON specification.
  762. :param bool as_string: If True, serialize to a string instead of a Python
  763. `decimal.Decimal` type.
  764. :param kwargs: The same keyword arguments that :class:`Number` receives.
  765. .. versionadded:: 1.2.0
  766. """
  767. num_type = decimal.Decimal
  768. default_error_messages = {
  769. 'special': 'Special numeric values (nan or infinity) are not permitted.',
  770. }
  771. def __init__(
  772. self, places=None, rounding=None, allow_nan=False, as_string=False, **kwargs
  773. ):
  774. self.places = (
  775. decimal.Decimal((0, (1,), -places)) if places is not None else None
  776. )
  777. self.rounding = rounding
  778. self.allow_nan = allow_nan
  779. super(Decimal, self).__init__(as_string=as_string, **kwargs)
  780. # override Number
  781. def _format_num(self, value):
  782. num = decimal.Decimal(str(value))
  783. if self.allow_nan:
  784. if num.is_nan():
  785. return decimal.Decimal('NaN') # avoid sNaN, -sNaN and -NaN
  786. else:
  787. if num.is_nan() or num.is_infinite():
  788. self.fail('special')
  789. if self.places is not None and num.is_finite():
  790. num = num.quantize(self.places, rounding=self.rounding)
  791. return num
  792. # override Number
  793. def _validated(self, value):
  794. try:
  795. return super(Decimal, self)._validated(value)
  796. except decimal.InvalidOperation:
  797. self.fail('invalid')
  798. # override Number
  799. def _to_string(self, value):
  800. return format(value, 'f')
  801. class Boolean(Field):
  802. """A boolean field.
  803. :param set truthy: Values that will (de)serialize to `True`. If an empty
  804. set, any non-falsy value will deserialize to `True`. If `None`,
  805. `marshmallow.fields.Boolean.truthy` will be used.
  806. :param set falsy: Values that will (de)serialize to `False`. If `None`,
  807. `marshmallow.fields.Boolean.falsy` will be used.
  808. :param kwargs: The same keyword arguments that :class:`Field` receives.
  809. """
  810. #: Default truthy values.
  811. truthy = {
  812. 't',
  813. 'T',
  814. 'true',
  815. 'True',
  816. 'TRUE',
  817. 'on',
  818. 'On',
  819. 'ON',
  820. 'y',
  821. 'Y',
  822. 'yes',
  823. 'Yes',
  824. 'YES',
  825. '1',
  826. 1,
  827. True,
  828. }
  829. #: Default falsy values.
  830. falsy = {
  831. 'f',
  832. 'F',
  833. 'false',
  834. 'False',
  835. 'FALSE',
  836. 'off',
  837. 'Off',
  838. 'OFF',
  839. 'n',
  840. 'N',
  841. 'no',
  842. 'No',
  843. 'NO',
  844. '0',
  845. 0,
  846. 0.0,
  847. False,
  848. }
  849. default_error_messages = {'invalid': 'Not a valid boolean.'}
  850. def __init__(self, truthy=None, falsy=None, **kwargs):
  851. super(Boolean, self).__init__(**kwargs)
  852. if truthy is not None:
  853. self.truthy = set(truthy)
  854. if falsy is not None:
  855. self.falsy = set(falsy)
  856. def _serialize(self, value, attr, obj, **kwargs):
  857. if value is None:
  858. return None
  859. elif value in self.truthy:
  860. return True
  861. elif value in self.falsy:
  862. return False
  863. return bool(value)
  864. def _deserialize(self, value, attr, data, **kwargs):
  865. if not self.truthy:
  866. return bool(value)
  867. else:
  868. try:
  869. if value in self.truthy:
  870. return True
  871. elif value in self.falsy:
  872. return False
  873. except TypeError:
  874. pass
  875. self.fail('invalid', input=value)
  876. class DateTime(Field):
  877. """A formatted datetime string in UTC.
  878. Example: ``'2014-12-22T03:12:58.019077+00:00'``
  879. Timezone-naive `datetime` objects are converted to
  880. UTC (+00:00) by :meth:`Schema.dump <marshmallow.Schema.dump>`.
  881. :meth:`Schema.load <marshmallow.Schema.load>` returns `datetime`
  882. objects that are timezone-aware.
  883. :param str format: Either ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601),
  884. or a date format string. If `None`, defaults to "iso".
  885. :param kwargs: The same keyword arguments that :class:`Field` receives.
  886. """
  887. SERIALIZATION_FUNCS = {
  888. 'iso': utils.isoformat,
  889. 'iso8601': utils.isoformat,
  890. 'rfc': utils.rfcformat,
  891. 'rfc822': utils.rfcformat,
  892. }
  893. DESERIALIZATION_FUNCS = {
  894. 'iso': utils.from_iso_datetime,
  895. 'iso8601': utils.from_iso_datetime,
  896. 'rfc': utils.from_rfc,
  897. 'rfc822': utils.from_rfc,
  898. }
  899. DEFAULT_FORMAT = 'iso'
  900. OBJ_TYPE = 'datetime'
  901. SCHEMA_OPTS_VAR_NAME = 'datetimeformat'
  902. localtime = False
  903. default_error_messages = {
  904. 'invalid': 'Not a valid {obj_type}.',
  905. 'format': '"{input}" cannot be formatted as a {obj_type}.',
  906. }
  907. def __init__(self, format=None, **kwargs):
  908. super(DateTime, self).__init__(**kwargs)
  909. # Allow this to be None. It may be set later in the ``_serialize``
  910. # or ``_deserialize`` methods This allows a Schema to dynamically set the
  911. # format, e.g. from a Meta option
  912. self.format = format
  913. def _bind_to_schema(self, field_name, schema):
  914. super(DateTime, self)._bind_to_schema(field_name, schema)
  915. self.format = (
  916. self.format or
  917. getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME) or
  918. self.DEFAULT_FORMAT
  919. )
  920. def _serialize(self, value, attr, obj, **kwargs):
  921. if value is None:
  922. return None
  923. data_format = self.format or self.DEFAULT_FORMAT
  924. format_func = self.SERIALIZATION_FUNCS.get(data_format)
  925. if format_func:
  926. try:
  927. return format_func(value, localtime=self.localtime)
  928. except (TypeError, AttributeError, ValueError):
  929. self.fail('format', input=value, obj_type=self.OBJ_TYPE)
  930. else:
  931. return value.strftime(data_format)
  932. def _deserialize(self, value, attr, data, **kwargs):
  933. if not value: # Falsy values, e.g. '', None, [] are not valid
  934. raise self.fail('invalid', input=value, obj_type=self.OBJ_TYPE)
  935. data_format = self.format or self.DEFAULT_FORMAT
  936. func = self.DESERIALIZATION_FUNCS.get(data_format)
  937. if func:
  938. try:
  939. return func(value)
  940. except (TypeError, AttributeError, ValueError):
  941. raise self.fail('invalid', input=value, obj_type=self.OBJ_TYPE)
  942. else:
  943. try:
  944. return self._make_object_from_format(value, data_format)
  945. except (TypeError, AttributeError, ValueError):
  946. raise self.fail('invalid', input=value, obj_type=self.OBJ_TYPE)
  947. @staticmethod
  948. def _make_object_from_format(value, data_format):
  949. return dt.datetime.strptime(value, data_format)
  950. class LocalDateTime(DateTime):
  951. """A formatted datetime string in localized time, relative to UTC.
  952. ex. ``"Sun, 10 Nov 2013 08:23:45 -0600"``
  953. Takes the same arguments as :class:`DateTime <marshmallow.fields.DateTime>`.
  954. """
  955. localtime = True
  956. class Time(Field):
  957. """ISO8601-formatted time string.
  958. :param kwargs: The same keyword arguments that :class:`Field` receives.
  959. """
  960. default_error_messages = {
  961. 'invalid': 'Not a valid time.',
  962. 'format': '"{input}" cannot be formatted as a time.',
  963. }
  964. def _serialize(self, value, attr, obj, **kwargs):
  965. if value is None:
  966. return None
  967. try:
  968. ret = value.isoformat()
  969. except AttributeError:
  970. self.fail('format', input=value)
  971. if value.microsecond:
  972. return ret[:15]
  973. return ret
  974. def _deserialize(self, value, attr, data, **kwargs):
  975. """Deserialize an ISO8601-formatted time to a :class:`datetime.time` object."""
  976. if not value: # falsy values are invalid
  977. self.fail('invalid')
  978. try:
  979. return utils.from_iso_time(value)
  980. except (AttributeError, TypeError, ValueError):
  981. self.fail('invalid')
  982. class Date(DateTime):
  983. """ISO8601-formatted date string.
  984. :param format: Either ``"iso"`` (for ISO8601) or a date format string.
  985. If `None`, defaults to "iso".
  986. :param kwargs: The same keyword arguments that :class:`Field` receives.
  987. """
  988. default_error_messages = {
  989. 'invalid': 'Not a valid date.',
  990. 'format': '"{input}" cannot be formatted as a date.',
  991. }
  992. SERIALIZATION_FUNCS = {'iso': utils.to_iso_date, 'iso8601': utils.to_iso_date}
  993. DESERIALIZATION_FUNCS = {'iso': utils.from_iso_date, 'iso8601': utils.from_iso_date}
  994. DEFAULT_FORMAT = 'iso'
  995. OBJ_TYPE = 'date'
  996. SCHEMA_OPTS_VAR_NAME = 'dateformat'
  997. @staticmethod
  998. def _make_object_from_format(value, data_format):
  999. return dt.datetime.strptime(value, data_format).date()
  1000. class TimeDelta(Field):
  1001. """A field that (de)serializes a :class:`datetime.timedelta` object to an
  1002. integer and vice versa. The integer can represent the number of days,
  1003. seconds or microseconds.
  1004. :param str precision: Influences how the integer is interpreted during
  1005. (de)serialization. Must be 'days', 'seconds', 'microseconds',
  1006. 'milliseconds', 'minutes', 'hours' or 'weeks'.
  1007. :param str error: Error message stored upon validation failure.
  1008. :param kwargs: The same keyword arguments that :class:`Field` receives.
  1009. .. versionchanged:: 2.0.0
  1010. Always serializes to an integer value to avoid rounding errors.
  1011. Add `precision` parameter.
  1012. """
  1013. DAYS = 'days'
  1014. SECONDS = 'seconds'
  1015. MICROSECONDS = 'microseconds'
  1016. MILLISECONDS = 'milliseconds'
  1017. MINUTES = 'minutes'
  1018. HOURS = 'hours'
  1019. WEEKS = 'weeks'
  1020. default_error_messages = {
  1021. 'invalid': 'Not a valid period of time.',
  1022. 'format': '{input!r} cannot be formatted as a timedelta.',
  1023. }
  1024. def __init__(self, precision='seconds', error=None, **kwargs):
  1025. precision = precision.lower()
  1026. units = (
  1027. self.DAYS,
  1028. self.SECONDS,
  1029. self.MICROSECONDS,
  1030. self.MILLISECONDS,
  1031. self.MINUTES,
  1032. self.HOURS,
  1033. self.WEEKS,
  1034. )
  1035. if precision not in units:
  1036. msg = 'The precision must be {0} or "{1}".'.format(
  1037. ', '.join(['"{}"'.format(each) for each in units[:-1]]), units[-1],
  1038. )
  1039. raise ValueError(msg)
  1040. self.precision = precision
  1041. super(TimeDelta, self).__init__(error=error, **kwargs)
  1042. def _serialize(self, value, attr, obj, **kwargs):
  1043. if value is None:
  1044. return None
  1045. try:
  1046. base_unit = dt.timedelta(**{self.precision: 1})
  1047. return int(value.total_seconds() / base_unit.total_seconds())
  1048. except AttributeError:
  1049. self.fail('format', input=value)
  1050. def _deserialize(self, value, attr, data, **kwargs):
  1051. try:
  1052. value = int(value)
  1053. except (TypeError, ValueError):
  1054. self.fail('invalid')
  1055. kwargs = {self.precision: value}
  1056. try:
  1057. return dt.timedelta(**kwargs)
  1058. except OverflowError:
  1059. self.fail('invalid')
  1060. class Mapping(Field):
  1061. """An abstract class for objects with key-value pairs.
  1062. :param Field keys: A field class or instance for dict keys.
  1063. :param Field values: A field class or instance for dict values.
  1064. :param kwargs: The same keyword arguments that :class:`Field` receives.
  1065. .. note::
  1066. When the structure of nested data is not known, you may omit the
  1067. `keys` and `values` arguments to prevent content validation.
  1068. .. versionadded:: 3.0.0rc4
  1069. """
  1070. mapping_type = dict
  1071. default_error_messages = {'invalid': 'Not a valid mapping type.'}
  1072. def __init__(self, keys=None, values=None, **kwargs):
  1073. super(Mapping, self).__init__(**kwargs)
  1074. if keys is None:
  1075. self.key_container = None
  1076. else:
  1077. try:
  1078. self.key_container = resolve_field_instance(keys)
  1079. except FieldInstanceResolutionError:
  1080. raise ValueError(
  1081. '"keys" must be a subclass or instance of '
  1082. 'marshmallow.base.FieldABC.',
  1083. )
  1084. if values is None:
  1085. self.value_container = None
  1086. else:
  1087. try:
  1088. self.value_container = resolve_field_instance(values)
  1089. except FieldInstanceResolutionError:
  1090. raise ValueError(
  1091. '"values" must be a subclass or instance of '
  1092. 'marshmallow.base.FieldABC.',
  1093. )
  1094. def _bind_to_schema(self, field_name, schema):
  1095. super(Mapping, self)._bind_to_schema(field_name, schema)
  1096. if self.value_container:
  1097. self.value_container = copy.deepcopy(self.value_container)
  1098. self.value_container.parent = self
  1099. self.value_container.name = field_name
  1100. if self.key_container:
  1101. self.key_container = copy.deepcopy(self.key_container)
  1102. self.key_container.parent = self
  1103. self.key_container.name = field_name
  1104. def _serialize(self, value, attr, obj, **kwargs):
  1105. if value is None:
  1106. return None
  1107. if not self.value_container and not self.key_container:
  1108. return value
  1109. if not isinstance(value, _Mapping):
  1110. self.fail('invalid')
  1111. #  Serialize keys
  1112. if self.key_container is None:
  1113. keys = {k: k for k in value.keys()}
  1114. else:
  1115. keys = {
  1116. k: self.key_container._serialize(k, None, None, **kwargs)
  1117. for k in value.keys()
  1118. }
  1119. #  Serialize values
  1120. result = self.mapping_type()
  1121. if self.value_container is None:
  1122. for k, v in iteritems(value):
  1123. if k in keys:
  1124. result[keys[k]] = v
  1125. else:
  1126. for k, v in iteritems(value):
  1127. result[keys[k]] = self.value_container._serialize(
  1128. v, None, None, **kwargs
  1129. )
  1130. return result
  1131. def _deserialize(self, value, attr, data, **kwargs):
  1132. if not isinstance(value, _Mapping):
  1133. self.fail('invalid')
  1134. if not self.value_container and not self.key_container:
  1135. return value
  1136. errors = collections.defaultdict(dict)
  1137. #  Deserialize keys
  1138. if self.key_container is None:
  1139. keys = {k: k for k in value.keys()}
  1140. else:
  1141. keys = {}
  1142. for key in value.keys():
  1143. try:
  1144. keys[key] = self.key_container.deserialize(key)
  1145. except ValidationError as error:
  1146. errors[key]['key'] = error.messages
  1147. #  Deserialize values
  1148. result = self.mapping_type()
  1149. if self.value_container is None:
  1150. for k, v in iteritems(value):
  1151. if k in keys:
  1152. result[keys[k]] = v
  1153. else:
  1154. for key, val in iteritems(value):
  1155. try:
  1156. deser_val = self.value_container.deserialize(val)
  1157. except ValidationError as error:
  1158. errors[key]['value'] = error.messages
  1159. if error.valid_data is not None and key in keys:
  1160. result[keys[key]] = error.valid_data
  1161. else:
  1162. if key in keys:
  1163. result[keys[key]] = deser_val
  1164. if errors:
  1165. raise ValidationError(errors, valid_data=result)
  1166. return result
  1167. class Dict(Mapping):
  1168. """A dict field. Supports dicts and dict-like objects. Extends
  1169. Mapping with dict as the mapping_type.
  1170. Example: ::
  1171. numbers = fields.Dict(keys=fields.Str(), values=fields.Float())
  1172. :param kwargs: The same keyword arguments that :class:`Mapping` receives.
  1173. .. versionadded:: 2.1.0
  1174. """
  1175. mapping_type = dict
  1176. class Url(String):
  1177. """A validated URL field. Validation occurs during both serialization and
  1178. deserialization.
  1179. :param default: Default value for the field if the attribute is not set.
  1180. :param str attribute: The name of the attribute to get the value from. If
  1181. `None`, assumes the attribute has the same name as the field.
  1182. :param bool relative: Allow relative URLs.
  1183. :param kwargs: The same keyword arguments that :class:`String` receives.
  1184. """
  1185. default_error_messages = {'invalid': 'Not a valid URL.'}
  1186. def __init__(self, relative=False, schemes=None, require_tld=True, **kwargs):
  1187. String.__init__(self, **kwargs)
  1188. self.relative = relative
  1189. self.require_tld = require_tld
  1190. # Insert validation into self.validators so that multiple errors can be
  1191. # stored.
  1192. self.validators.insert(
  1193. 0,
  1194. validate.URL(
  1195. relative=self.relative,
  1196. schemes=schemes,
  1197. require_tld=self.require_tld,
  1198. error=self.error_messages['invalid'],
  1199. ),
  1200. )
  1201. def _validated(self, value):
  1202. if value is None:
  1203. return None
  1204. return validate.URL(
  1205. relative=self.relative,
  1206. require_tld=self.require_tld,
  1207. error=self.error_messages['invalid'],
  1208. )(value)
  1209. class Email(String):
  1210. """A validated email field. Validation occurs during both serialization and
  1211. deserialization.
  1212. :param args: The same positional arguments that :class:`String` receives.
  1213. :param kwargs: The same keyword arguments that :class:`String` receives.
  1214. """
  1215. default_error_messages = {'invalid': 'Not a valid email address.'}
  1216. def __init__(self, *args, **kwargs):
  1217. String.__init__(self, *args, **kwargs)
  1218. # Insert validation into self.validators so that multiple errors can be
  1219. # stored.
  1220. self.validators.insert(0, validate.Email(error=self.error_messages['invalid']))
  1221. def _validated(self, value):
  1222. if value is None:
  1223. return None
  1224. return validate.Email(error=self.error_messages['invalid'])(value)
  1225. class Method(Field):
  1226. """A field that takes the value returned by a `Schema` method.
  1227. :param str serialize: The name of the Schema method from which
  1228. to retrieve the value. The method must take an argument ``obj``
  1229. (in addition to self) that is the object to be serialized.
  1230. :param str deserialize: Optional name of the Schema method for deserializing
  1231. a value The method must take a single argument ``value``, which is the
  1232. value to deserialize.
  1233. .. versionchanged:: 2.0.0
  1234. Removed optional ``context`` parameter on methods. Use ``self.context`` instead.
  1235. .. versionchanged:: 2.3.0
  1236. Deprecated ``method_name`` parameter in favor of ``serialize`` and allow
  1237. ``serialize`` to not be passed at all.
  1238. .. versionchanged:: 3.0.0
  1239. Removed ``method_name`` parameter.
  1240. """
  1241. _CHECK_ATTRIBUTE = False
  1242. def __init__(self, serialize=None, deserialize=None, **kwargs):
  1243. # Set dump_only and load_only based on arguments
  1244. kwargs['dump_only'] = bool(serialize) and not bool(deserialize)
  1245. kwargs['load_only'] = bool(deserialize) and not bool(serialize)
  1246. super(Method, self).__init__(**kwargs)
  1247. self.serialize_method_name = serialize
  1248. self.deserialize_method_name = deserialize
  1249. def _serialize(self, value, attr, obj, **kwargs):
  1250. if not self.serialize_method_name:
  1251. return missing_
  1252. method = utils.callable_or_raise(
  1253. getattr(self.parent, self.serialize_method_name, None),
  1254. )
  1255. return method(obj)
  1256. def _deserialize(self, value, attr, data, **kwargs):
  1257. if self.deserialize_method_name:
  1258. method = utils.callable_or_raise(
  1259. getattr(self.parent, self.deserialize_method_name, None),
  1260. )
  1261. return method(value)
  1262. return value
  1263. class Function(Field):
  1264. """A field that takes the value returned by a function.
  1265. :param callable serialize: A callable from which to retrieve the value.
  1266. The function must take a single argument ``obj`` which is the object
  1267. to be serialized. It can also optionally take a ``context`` argument,
  1268. which is a dictionary of context variables passed to the serializer.
  1269. If no callable is provided then the ```load_only``` flag will be set
  1270. to True.
  1271. :param callable deserialize: A callable from which to retrieve the value.
  1272. The function must take a single argument ``value`` which is the value
  1273. to be deserialized. It can also optionally take a ``context`` argument,
  1274. which is a dictionary of context variables passed to the deserializer.
  1275. If no callable is provided then ```value``` will be passed through
  1276. unchanged.
  1277. .. versionchanged:: 2.3.0
  1278. Deprecated ``func`` parameter in favor of ``serialize``.
  1279. .. versionchanged:: 3.0.0a1
  1280. Removed ``func`` parameter.
  1281. """
  1282. _CHECK_ATTRIBUTE = False
  1283. def __init__(self, serialize=None, deserialize=None, func=None, **kwargs):
  1284. # Set dump_only and load_only based on arguments
  1285. kwargs['dump_only'] = bool(serialize) and not bool(deserialize)
  1286. kwargs['load_only'] = bool(deserialize) and not bool(serialize)
  1287. super(Function, self).__init__(**kwargs)
  1288. self.serialize_func = serialize and utils.callable_or_raise(serialize)
  1289. self.deserialize_func = deserialize and utils.callable_or_raise(deserialize)
  1290. def _serialize(self, value, attr, obj, **kwargs):
  1291. return self._call_or_raise(self.serialize_func, obj, attr)
  1292. def _deserialize(self, value, attr, data, **kwargs):
  1293. if self.deserialize_func:
  1294. return self._call_or_raise(self.deserialize_func, value, attr)
  1295. return value
  1296. def _call_or_raise(self, func, value, attr):
  1297. if len(utils.get_func_args(func)) > 1:
  1298. if self.parent.context is None:
  1299. msg = 'No context available for Function field {0!r}'.format(attr)
  1300. raise ValidationError(msg)
  1301. return func(value, self.parent.context)
  1302. else:
  1303. return func(value)
  1304. class Constant(Field):
  1305. """A field that (de)serializes to a preset constant. If you only want the
  1306. constant added for serialization or deserialization, you should use
  1307. ``dump_only=True`` or ``load_only=True`` respectively.
  1308. :param constant: The constant to return for the field attribute.
  1309. .. versionadded:: 2.0.0
  1310. """
  1311. _CHECK_ATTRIBUTE = False
  1312. def __init__(self, constant, **kwargs):
  1313. super(Constant, self).__init__(**kwargs)
  1314. self.constant = constant
  1315. self.missing = constant
  1316. self.default = constant
  1317. def _serialize(self, value, *args, **kwargs):
  1318. return self.constant
  1319. def _deserialize(self, value, *args, **kwargs):
  1320. return self.constant
  1321. class Inferred(Field):
  1322. """A field that infers how to serialize, based on the value type.
  1323. .. warning::
  1324. This class is treated as private API.
  1325. Users should not need to use this class directly.
  1326. """
  1327. def __init__(self):
  1328. super(Inferred, self).__init__()
  1329. # We memoize the fields to avoid creating and binding new fields
  1330. # every time on serialization.
  1331. self._field_cache = {}
  1332. def _serialize(self, value, attr, obj, **kwargs):
  1333. field_cls = self.root.TYPE_MAPPING.get(type(value))
  1334. if field_cls is None:
  1335. field = super(Inferred, self)
  1336. else:
  1337. field = self._field_cache.get(field_cls)
  1338. if field is None:
  1339. field = field_cls()
  1340. field._bind_to_schema(self.name, self.parent)
  1341. self._field_cache[field_cls] = field
  1342. return field._serialize(value, attr, obj, **kwargs)
  1343. # Aliases
  1344. URL = Url
  1345. Str = String
  1346. Bool = Boolean
  1347. Int = Integer