Skip to content

Instantly share code, notes, and snippets.

@nicolaiarocci
Created January 5, 2015 10:09
Show Gist options
  • Select an option

  • Save nicolaiarocci/829c98eb5f8b4e9c96c1 to your computer and use it in GitHub Desktop.

Select an option

Save nicolaiarocci/829c98eb5f8b4e9c96c1 to your computer and use it in GitHub Desktop.

Revisions

  1. nicolaiarocci created this gist Jan 5, 2015.
    32 changes: 32 additions & 0 deletions validate_objects.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    import copy

    from cerberus import Validator
    from cerberus import errors

    from collections import Mapping, Sequence


    class ObjectValidator(Validator):
    def __init__(self, *args, **kwargs):
    self.allow_unknown = True
    super(ObjectValidator, self).__init__(*args, **kwargs)

    def validate_object(self, obj):
    return self.validate(obj.__dict__)

    def _validate_type_object(self, field, value):
    # objects which are not Mapping or Sequence types are allowed.
    # (Mapping and Sequence types are dealt elsewhere.)
    if not (isinstance(value, object) and \
    not isinstance(value, (Sequence, Mapping))):
    self._error(field, errors.ERROR_BAD_TYPE % "object")

    def _validate_schema(self, schema, field, value):
    if isinstance(value, (Sequence, Mapping)):
    super(ObjectValidator, self)._validate_schema(schema, field, value)
    elif isinstance(value, object):
    validator = copy.copy(self)
    validator.schema = schema
    validator.validate(value.__dict__, context=self.document)
    if len(validator.errors):
    self._error(field, validator.errors)