Skip to content

Commit

Permalink
Rename @validator to @validates_schema
Browse files Browse the repository at this point in the history
See comments in #116
  • Loading branch information
sloria committed May 26, 2015
1 parent 0278918 commit c780b5c
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 29 deletions.
6 changes: 3 additions & 3 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ Changelog

Features:

- Add ``marshmallow.validator`` decorator for defining schema-level validators (:issue:`116`).
- Add ``marshmallow.validates_schema`` decorator for defining schema-level validators (:issue:`116`).
- Performance improvements.
- Defining ``__marshallable__`` on complex objects is no longer necessary.

Deprecation/Removals:

- Remove ``skip_missing`` class Meta option. By default, missing inputs are excluded from serialized output (:issue:`211`).
- Remove optional ``context`` parameter that gets passed to methods for ``Method`` fields.
- ``Schema.validator`` is deprecated. Use ``marshmallow.validator`` instead.
- ``Schema.validator`` is deprecated. Use ``marshmallow.validates_schema`` instead.
- ``utils.get_func_name`` is removed. Use ``utils.get_callable_name`` instead.

Bug fixes:
Expand All @@ -34,7 +34,7 @@ Changes from 2.0.0b2:

- ``Boolean`` field serializes ``None`` to ``None``, for consistency with other fields (:issue:`213`). Thanks :user:`cmanallen` for reporting.
- Bug fix: ``load_only`` fields do not get validated during serialization.
- Implicit passing of original, raw data to Schema validators is removed. Use ``@marshmallow.validator(pass_original=True)`` instead.
- Implicit passing of original, raw data to Schema validators is removed. Use ``@marshmallow.validates_schema(pass_original=True)`` instead.

2.0.0b2 (2015-05-03)
++++++++++++++++++++
Expand Down
12 changes: 6 additions & 6 deletions docs/extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,17 @@ You can register a custom error-handling function for a :class:`Schema` using th
Schema-level Validation
-----------------------

You can register schema-level validation functions for a :class:`Schema` using the :meth:`marshmallow.validator <marshmallow.decorators.validator>` decorator. Schema-level validation errors will be stored on the ``_schema`` key of the errors dictonary.
You can register schema-level validation functions for a :class:`Schema` using the :meth:`marshmallow.validates_schema <marshmallow.decorators.validates_schema>` decorator. Schema-level validation errors will be stored on the ``_schema`` key of the errors dictonary.

.. code-block:: python
from marshmallow import Schema, fields, validator, ValidationError
from marshmallow import Schema, fields, validates_schema, ValidationError
class NumberSchema(Schema):
field_a = fields.Integer()
field_b = fields.Integer()
@validator
@validates_schema
def validate_numbers(self, data):
if data['field_b'] >= data['field_a']:
raise ValidationError('field_a must be greater than field_b')
Expand All @@ -204,7 +204,7 @@ You can register schema-level validation functions for a :class:`Schema` using t
Validating Original Input Data
++++++++++++++++++++++++++++++

Normally, unspecified field names are ignored by the validator. If you would like access to the original, raw input (e.g. to fail validation if an unknown field name is sent), add ``pass_original=True`` to your call to `validator <marshmallow.decorators.validator>`.
Normally, unspecified field names are ignored by the validator. If you would like access to the original, raw input (e.g. to fail validation if an unknown field name is sent), add ``pass_original=True`` to your call to `validates_schema <marshmallow.decorators.validates_schema>`.

.. code-block:: python
:emphasize-lines: 5
Expand All @@ -213,7 +213,7 @@ Normally, unspecified field names are ignored by the validator. If you would lik
foo = fields.Int()
bar = fields.Int()
@validator(pass_original=True)
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
for key in original_data:
if key not in schema.fields:
Expand All @@ -236,7 +236,7 @@ If you want to store schema-level validation errors on a specific field, you can
field_a = fields.Integer()
field_b = fields.Integer()
@validator
@validates_schema
def validate_numbers(self, data):
if data['field_b'] >= data['field_a']:
raise ValidationError(
Expand Down
4 changes: 2 additions & 2 deletions marshmallow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
MarshalResult,
UnmarshalResult,
)
from marshmallow.decorators import pre_dump, post_dump, pre_load, post_load, validator
from marshmallow.decorators import pre_dump, post_dump, pre_load, post_load, validates_schema
from marshmallow.utils import pprint, missing
from marshmallow.exceptions import MarshallingError, UnmarshallingError, ValidationError

Expand All @@ -18,7 +18,7 @@
__all__ = [
'Schema',
'SchemaOpts',
'validator',
'validates_schema',
'pre_dump',
'post_dump',
'pre_load',
Expand Down
12 changes: 6 additions & 6 deletions marshmallow/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Example: ::
from marshmallow import (
Schema, pre_load, pre_dump, post_load, validator, ValidationError
Schema, pre_load, pre_dump, post_load, validates_schema, ValidationError
)
class UserSchema(Schema):
Expand All @@ -27,7 +27,7 @@ def add_envelope(self, data, many):
namespace = 'results' if many else 'result'
return {namespace: data}
@validator
@validates_schema
def validate_email(self, data):
if len(data['email']) < 3:
raise ValidationError('Email must be more than 3 characters', 'email')
Expand All @@ -41,10 +41,10 @@ def validate_email(self, data):
POST_DUMP = 'post_dump'
PRE_LOAD = 'pre_load'
POST_LOAD = 'post_load'
VALIDATOR = 'validator'
VALIDATES_SCHEMA = 'validates_schema'

def validator(fn=None, raw=False, pass_original=False):
"""Register a schema-level validator method.
def validates_schema(fn=None, raw=False, pass_original=False):
"""Register a schema-level validates_schema method.
By default, receives a single object at a time, regardless of whether ``many=True``
is passed to the `Schema`. If ``raw=True``, the raw data (which may be a collection)
Expand All @@ -53,7 +53,7 @@ def validator(fn=None, raw=False, pass_original=False):
If ``pass_original=True``, the original data (before unmarshalling) will be passed as
an additional argument to the method.
"""
return tag_processor(VALIDATOR, fn, raw, pass_original=pass_original)
return tag_processor(VALIDATES_SCHEMA, fn, raw, pass_original=pass_original)

def pre_dump(fn=None, raw=False):
"""Register a method to invoke before serializing an object. The method
Expand Down
10 changes: 5 additions & 5 deletions marshmallow/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from marshmallow.compat import (with_metaclass, iteritems, text_type,
binary_type, OrderedDict)
from marshmallow.orderedset import OrderedSet
from marshmallow.decorators import PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD, VALIDATOR
from marshmallow.decorators import PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD, VALIDATES_SCHEMA


#: Return type of :meth:`Schema.dump` including serialized data and errors
Expand Down Expand Up @@ -438,10 +438,10 @@ def validator(cls, func):
.. versionadded:: 1.0
.. deprecated:: 2.0.0
Use `marshmallow.validator <marshmallow.decorators.validator>` instead.
Use `marshmallow.validates_schema <marshmallow.decorators.validates_schema>` instead.
"""
warnings.warn(
'Schema.validator is deprecated. Use the marshmallow.validator decorator '
'Schema.validator is deprecated. Use the marshmallow.validates_schema decorator '
'instead.', category=DeprecationWarning
)
cls.__validators__ = cls.__validators__ or []
Expand Down Expand Up @@ -737,9 +737,9 @@ def _invoke_load_processors(self, tag_name, data, many):
return data

def _invoke_validators(self, raw, data, original_data, many):
for attr_name in self.__processors__[(VALIDATOR, raw)]:
for attr_name in self.__processors__[(VALIDATES_SCHEMA, raw)]:
validator = getattr(self, attr_name)
validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATOR, raw)]
validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, raw)]
pass_original = validator_kwargs.get('pass_original', False)
if raw:
validator = partial(validator, many=many)
Expand Down
14 changes: 7 additions & 7 deletions tests/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
post_dump,
pre_load,
post_load,
validator,
validates_schema,
ValidationError,
)

Expand Down Expand Up @@ -117,26 +117,26 @@ def overridden(item):
}


class TestValidatorDecorator:
class TestValidatesSchmeaDecorator:

def test_decorated_validators(self):

class MySchema(Schema):
foo = fields.Int()
bar = fields.Int()

@validator
@validates_schema
def validate_schema(self, data):
if data['foo'] <= 3:
raise ValidationError('Must be greater than 3')

@validator(raw=True)
@validates_schema(raw=True)
def validate_raw(self, data, many):
if many:
if len(data) < 2:
raise ValidationError('Must provide at least 2 items')

@validator
@validates_schema
def validate_bar(self, data):
if 'bar' in data and data['bar'] < 0:
raise ValidationError('bar must not be negative', 'bar')
Expand All @@ -162,13 +162,13 @@ class MySchema(Schema):
foo = fields.Int()
bar = fields.Int()

@validator(pass_original=True)
@validates_schema(pass_original=True)
def validate_original(self, data, original_data):
if isinstance(original_data, dict) and isinstance(original_data['foo'], str):
raise ValidationError('foo cannot be a string')

# See https://github.com/marshmallow-code/marshmallow/issues/127
@validator(raw=True, pass_original=True)
@validates_schema(raw=True, pass_original=True)
def check_unknown_fields(self, data, original_data, many):
def check(datum):
for key, val in datum.items():
Expand Down

0 comments on commit c780b5c

Please sign in to comment.