Example #1
0
class PersonSchema(ObjectSchema):
    id = Integer()
    name = String()
    dob = DateTime(format='%Y-%m-%dT%H:%M:%S')
    title = String(optional=True)
    address = EnsureType("Address")
    jobs = List(EnsureType("Job"))
Example #2
0
    def test_ensuretype_validator(self):
        v = EnsureType((int, float))
        self.assertEqual(42.0, v.validate(42.0))
        self.assertEqual(42, v.validate(42))

        with self.assertRaises(ValidationError) as c:
            v.validate("foo")

        exc = c.exception
        self.assertEqual("Expected one of (int, float) got str instead.", str(exc))
        self.assertEqual("invalid_type", exc.reason_code)
Example #3
0
def loader(json_str, **kw):
    """
    Call this function as you would call :func:`json.loads`. It wraps the
    :ref:`object_hook` interface and returns python class instances from JSON
    strings.
    
    :param ensure_type: Check that the resulting object is of type
        ``ensure_type``. Raise a ValidationError otherwise.          
    :param handlers: is a dict of handlers. see :func:`object_hook`.    
    :param as_type: explicitly specify the type of object the JSON
        represents. see :func:`object_hook`    
    :param validate: Set to False to turn off validation (ie dont run the
        schemas) during this load operation. Defaults to True.    
    :param kw: the rest of the kw args will be passed to the underlying
        :func:`json.loads` calls.
    
    
    """
    kw["object_hook"] = object_hook(kw.pop("handlers", None),
                                    kw.pop("as_type", None),
                                    kw.pop("validate", True))

    ensure_type = kw.pop("ensure_type", _as_type_context.top)

    try:
        obj = json.loads(json_str, **kw)
    except ValueError as e:
        raise JsonDecodeError(e.args[0])

    if ensure_type:
        return EnsureType(ensure_type).validate(obj)
    return obj
Example #4
0
    def test_ensuretype_validator(self):
        v = EnsureType((int, float))
        self.assertEqual(42.0, v.validate(42.0))
        self.assertEqual(42, v.validate(42))

        with self.assertRaises(ValidationError) as c:
            v.validate("foo")

        exc = c.exception
        self.assertEqual("Expected one of (int, float) got str instead.",
                         str(exc))
        self.assertEqual("invalid_type", exc.reason_code)
Example #5
0
 class FooSchema(ObjectSchema):
     bar = EnsureType("Bar", optional=True, nullable=True)
Example #6
0
 class JobSchema(ObjectSchema):
     title = String()
     id = EnsureType(Foo)
Example #7
0
 class PersonSchema(ObjectSchema):
     first_name = String()
     last_name = String()
     job = EnsureType("Job")
Example #8
0
 class TestRequestSchema(ObjectSchema):
     request_guid = String()
     players = List(EnsureType("Person"))