decorators.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # -*- coding: utf-8 -*-
  2. """Decorators for registering schema pre-processing and post-processing methods.
  3. These should be imported from the top-level `marshmallow` module.
  4. Example: ::
  5. from marshmallow import (
  6. Schema, pre_load, pre_dump, post_load, validates_schema,
  7. validates, fields, ValidationError
  8. )
  9. class UserSchema(Schema):
  10. email = fields.Str(required=True)
  11. age = fields.Integer(required=True)
  12. @post_load
  13. def lowerstrip_email(self, item):
  14. item['email'] = item['email'].lower().strip()
  15. return item
  16. @pre_load(pass_many=True)
  17. def remove_envelope(self, data, many):
  18. namespace = 'results' if many else 'result'
  19. return data[namespace]
  20. @post_dump(pass_many=True)
  21. def add_envelope(self, data, many):
  22. namespace = 'results' if many else 'result'
  23. return {namespace: data}
  24. @validates_schema
  25. def validate_email(self, data):
  26. if len(data['email']) < 3:
  27. raise ValidationError('Email must be more than 3 characters', 'email')
  28. @validates('age')
  29. def validate_age(self, data):
  30. if data < 14:
  31. raise ValidationError('Too young!')
  32. .. note::
  33. These decorators only work with instance methods. Class and static
  34. methods are not supported.
  35. .. warning::
  36. The invocation order of decorated methods of the same type is not guaranteed.
  37. If you need to guarantee order of different processing steps, you should put
  38. them in the same processing method.
  39. """
  40. from __future__ import unicode_literals
  41. import functools
  42. PRE_DUMP = 'pre_dump'
  43. POST_DUMP = 'post_dump'
  44. PRE_LOAD = 'pre_load'
  45. POST_LOAD = 'post_load'
  46. VALIDATES = 'validates'
  47. VALIDATES_SCHEMA = 'validates_schema'
  48. def validates(field_name):
  49. """Register a field validator.
  50. :param str field_name: Name of the field that the method validates.
  51. """
  52. return set_hook(None, VALIDATES, field_name=field_name)
  53. def validates_schema(
  54. fn=None,
  55. pass_many=False,
  56. pass_original=False,
  57. skip_on_field_errors=True,
  58. ):
  59. """Register a schema-level validator.
  60. By default, receives a single object at a time, regardless of whether ``many=True``
  61. is passed to the `Schema`. If ``pass_many=True``, the raw data (which may be a collection)
  62. and the value for ``many`` is passed.
  63. If ``pass_original=True``, the original data (before unmarshalling) will be passed as
  64. an additional argument to the method.
  65. If ``skip_on_field_errors=True``, this validation method will be skipped whenever
  66. validation errors have been detected when validating fields.
  67. .. versionchanged:: 3.0.0b1
  68. ``skip_on_field_errors`` defaults to `True`.
  69. """
  70. return set_hook(
  71. fn,
  72. (VALIDATES_SCHEMA, pass_many),
  73. pass_original=pass_original,
  74. skip_on_field_errors=skip_on_field_errors,
  75. )
  76. def pre_dump(fn=None, pass_many=False):
  77. """Register a method to invoke before serializing an object. The method
  78. receives the object to be serialized and returns the processed object.
  79. By default, receives a single object at a time, regardless of whether ``many=True``
  80. is passed to the `Schema`. If ``pass_many=True``, the raw data (which may be a collection)
  81. and the value for ``many`` is passed.
  82. """
  83. return set_hook(fn, (PRE_DUMP, pass_many))
  84. def post_dump(fn=None, pass_many=False, pass_original=False):
  85. """Register a method to invoke after serializing an object. The method
  86. receives the serialized object and returns the processed object.
  87. By default, receives a single object at a time, transparently handling the ``many``
  88. argument passed to the Schema. If ``pass_many=True``, the raw data
  89. (which may be a collection) and the value for ``many`` is passed.
  90. If ``pass_original=True``, the original data (before serializing) will be passed as
  91. an additional argument to the method.
  92. """
  93. return set_hook(fn, (POST_DUMP, pass_many), pass_original=pass_original)
  94. def pre_load(fn=None, pass_many=False):
  95. """Register a method to invoke before deserializing an object. The method
  96. receives the data to be deserialized and returns the processed data.
  97. By default, receives a single datum at a time, transparently handling the ``many``
  98. argument passed to the Schema. If ``pass_many=True``, the raw data
  99. (which may be a collection) and the value for ``many`` is passed.
  100. """
  101. return set_hook(fn, (PRE_LOAD, pass_many))
  102. def post_load(fn=None, pass_many=False, pass_original=False):
  103. """Register a method to invoke after deserializing an object. The method
  104. receives the deserialized data and returns the processed data.
  105. By default, receives a single datum at a time, transparently handling the ``many``
  106. argument passed to the Schema. If ``pass_many=True``, the raw data
  107. (which may be a collection) and the value for ``many`` is passed.
  108. If ``pass_original=True``, the original data (before deserializing) will be passed as
  109. an additional argument to the method.
  110. """
  111. return set_hook(fn, (POST_LOAD, pass_many), pass_original=pass_original)
  112. def set_hook(fn, key, **kwargs):
  113. """Mark decorated function as a hook to be picked up later.
  114. .. note::
  115. Currently only works with functions and instance methods. Class and
  116. static methods are not supported.
  117. :return: Decorated function if supplied, else this decorator with its args
  118. bound.
  119. """
  120. # Allow using this as either a decorator or a decorator factory.
  121. if fn is None:
  122. return functools.partial(set_hook, key=key, **kwargs)
  123. # Set a __marshmallow_hook__ attribute instead of wrapping in some class,
  124. # because I still want this to end up as a normal (unbound) method.
  125. try:
  126. hook_config = fn.__marshmallow_hook__
  127. except AttributeError:
  128. fn.__marshmallow_hook__ = hook_config = {}
  129. # Also save the kwargs for the tagged function on
  130. # __marshmallow_hook__, keyed by (<tag>, <pass_many>)
  131. hook_config[key] = kwargs
  132. return fn