Field Types
Many fields are provided out of the box.
StrField
Validates strings. Optionally will trim whitespace, and validate length.
IntField
Validates integers. Optionally will validate min and max values.
FloatField
Validates floats. Optionally will validate min and max values.
BoolField
ListField
Validates lists of a specific type. Optionally will validate length.
TupleField
Validates tuples of a specific type. A tuple may either have a single inner type and no length validation, or a tuple of inner types which are used to validate items positionally.
class TupleExample(Schema):
name_and_age: Tuple[str, int] = field(TupleField((StrField(), IntField())))
extra: Tuple[str, ...] = field(TupleField(StrField()))
DictField
Validates dicts with specific key and value types. If no Field
is provided
for the key or value, the key or value will be validated as Any
.
class DictExample(Schema):
name_to_age: Dict[str, int] = field(DictField(StrField(), IntField()))
any_dict: Dict[Any, Any] = field(DictField(None, None))
DateTimeField
Validates datetime.datetime
objects. Will attempt to parse strings into
datetime objects.
TimeDeltaField
Validates datetime.timedelta
objects. If an int
is provided, will convert
to a timedelta
with that many seconds.
TimezoneField
Validates datetime.tzinfo
objects. If a string is provided, will attempt to
convert to a tzinfo
using zoneinfo
(if on a supported python version).
EnumField
Validates enum.Enum
objects. Accepts either the enum value or an instance of
the enum. Optionally, a subset of valid options may be specified.
class MyEnum(enum.Enum):
FOO = "foo"
BAR = "bar"
class EnumExample(Schema):
my_enum: MyEnum = field(EnumField(MyEnum, valid_options=(MyEnum.FOO, )))
InstanceField
Validates the given value is an instance of a specific class.
class MyClass:
pass
class InstanceExample(Schema):
my_instance: MyClass = field(InstanceField(MyClass))
NestedField
Validates a nested schema or schema definition.
class NestedSchema(Schema):
name: str = field(StrField())
class NestedExample(Schema):
nested: NestedSchema = field(NestedField(NestedSchema))
SerializablePolymorphicField
Validates a field that may have values of a few different types, depending on a tag. The tag is a field on the object that is used to determine which set of validation to apply.
class Foo:
def __init__(self, foo: str):
self.foo = foo
class FooSchema(Schema):
foo: str = field(StrField())
class Bar:
def __init__(self, bar: int):
self.bar = bar
class BarSchema(Schema):
bar: int = field(IntField())
class PolymorphicExampleSchema(Schema):
my_subfield = SerializablePolymorphicField(
type_field="type",
mappings=[
PolySchemaMapping(
public_type="foo",
internal_type=Foo,
schema_cls=FooSchema,
serializer=lambda foo: {"foo": foo.foo},
factory=lambda schema: Foo(foo=schema.foo),
),
PolySchemaMapping(
public_type="bar",
internal_type=Bar,
schema_cls=BarSchema,
serializer=lambda bar: {"bar": bar.bar},
factory=lambda schema: Bar(bar=schema.bar),
),
],
)
result = clean(
PolymorphicExampleSchema,
{"my_subfield": {"type": "foo", "foo": "foo"}},
)
print(result)
# PolymorphicExampleSchema(my_subfield=Foo(foo='foo'))
print(serialize(result))
# {'my_subfield': {'type': 'foo', 'foo': 'foo'}}
RegexField
Validates a string against a regular expression.
URLField
Validates a string is a valid URL. Accepts options for:
* require_tld
(defaults to True
)
* default_scheme
* allowed_schemes
* disallowed_schemes
class URLExample(Schema):
url: str = field(
URLField(
require_tld=False,
default_scheme="http",
allowed_schemes=("http", "https"),
disallowed_schemes=("ftp",)
)
)
EmailField
Validates a string is a valid email address. Optionally a max length may be
specified (defaults to 254
).
UnionField
Validates a field against a union of possible types/fields. If a value already matches one of the union types, the associated field will be used for validation. If no options have a type match, validation will be attempted using each field in order, and the first to clean without error will be used.