FlyForms reference¶
Forms¶
Form
is the root class of FlyForms that provide the highest level API for
validation and mapping of data structures. All user-defined forms must inherit this class.
Form class¶
-
class
flyforms.form.
Form
[source]¶ Base class for all user-defined Forms
Construction
-
__init__
(**data)[source]¶ Parameters: data (dict) – additional data to form When a Form is instantiated you can access given data via instance attributes or get everything at once using
data
attribute
Note
Even if you do not pass some keys in
kwargs
, you can use instance attributes, but will receiveUNSET
valueProperties
-
is_bound
¶ Checks is Form instance bound. Returns True if all fields is bound. Otherwise, False.
-
is_valid
¶ Checks is Form instance valid. Returns there are no errors. Otherwise, False.
Attributes
-
_fields
¶ Python
set
contains all defined fields names
-
Defining Forms¶
Forms defining is quite simply process. All you need to do is to make a subclass of Form
and define fields as class attributes.
If you need to extend Forms, inheritance is available. New Form will contain all fields of the parent form as well as it’s own.
Using Forms¶
# coding=utf-8
from flyforms import Form, StringField, IntField
countries = (
"United Kingdom",
"United States",
"Russia",
"France",
"Germany"
)
class GreetingForm(Form):
first_name = StringField(
regex=r"^[A-Z].*$",
min_length=3,
max_length=64
)
last_name = StringField(
regex=r"^[A-Z].*$",
min_length=3,
max_length=64
)
country = StringField(choices=countries)
company = StringField(
required=False,
default="Home"
)
age = IntField(min_value=18)
if __name__ == '__main__':
form = GreetingForm(
first_name="John",
last_name="Smith",
age=33,
country="Germany"
)
print(form.is_bound) # >>> True
print(form.is_valid) # >>> True
print(form.errors) # >>> {}
print(form.data)
print(form.age) # >>> 33
print(form.company) # >>> Home
Form inwards¶
Todo
describe FormMeta
and FormField
In flight data validation¶
If you already have defined Form and you want to just validate some data structure via it you can use
validate_schema()
function from flyforms.form
module.
Usage¶
# coding=utf-8
from flyforms import validate_schema, Form, StringField, EmailField
class LoginForm(Form):
email = EmailField()
password = StringField(
min_length=8,
regex=r"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])",
max_length=64
)
if __name__ == '__main__':
# Valid data
r1 = validate_schema(LoginForm, email="smith@gmail.com", password="Qw3rT!y_")
print(r1) # >>> True
# Bad data
r2 = validate_schema(LoginForm, email="smith@gmail.com", password="Qwerty")
print(r2) # >>> False
Signature for validate_schema¶
-
flyforms.form.
validate_schema
(form_cls, **data)[source]¶ This function validates given data via given
Form
subclass without defined Form instantiation.Parameters: - form_cls (
Form
) – user-defined Form - data – data to validate
Returns: boolean flag is data valid for given
form_cls
Raises TypeError: if given
form_cls
is not class or notForm
subclass- form_cls (
Fields¶
Fields represent a set of rules to data validation via set of Validator
instances. When you define yours
custom Form
you define Fields as its class attributes.
This is the most common usage of Fields, but nothing prevents you to use them standalone.
Field class¶
-
class
flyforms.fields.
Field
[source]¶ Construction
-
__init__
(required=True, choices=(), validators=(), **kwargs)[source]¶ Parameters: - required (bool) – boolean flag is this field required or can be empty
- choices (iterable) – iterable object contains possible values of this field
- validators (list of callable) – the additional validators for field
- default (instance of value_types) – the default value of the field
Raises TypeError: if passed arguments invalid
Methods
-
validate
(value)[source]¶ Validates given value via defined set of
Validators
Parameters: value – the value to validate
-
is_valid
(value)[source]¶ The ‘silent’ variant of value validation.
Parameters: value – the value to validate Returns: True if given value is valid, otherwise - False
-
bind
(value)[source]¶ Validates and given value via defined set of
Validators
and returns it If value is mutable obj (for examplelist
) it’ll be converted to immutable (for exampletuple
)Parameters: value – the value to bind Returns: given value or field.default
if value isUNSET
New in version 0.2.0.
Attributes
-
required
¶ Boolean flag passed to constructor
-
base_validators
¶ List of attached by processing construction arguments
Validators
-
custom_validators
¶ Iterable object contains
custom_validators
passed to constructor
Property
-
validators
¶ Chain, contains
base_validators
andcustom_validators
-
Basic Fields¶
StringField¶
-
class
flyforms.fields.
StringField
(min_length=None, max_length=None, regex='', **kwargs)[source]¶ Reflects Python strings
-
__init__
(min_length=None, max_length=None, regex='', **kwargs)[source]¶ Parameters: - required (bool) – boolean flag is this field required
- min_length (int or None) – the minimum length of the string
- max_length (int or None) – the maximum length of the string
- regex (str or regexp) – the regular expression to validate
- choices (iterable) – iterable object contains possible values of this field
- validators (list of callable) – the additional validators for field
- default (instance of value_types) – the default value of the field
-
EmailField¶
-
class
flyforms.fields.
EmailField
(**kwargs)[source]¶ Reflects Python string corresponding to an email
-
__init__
(**kwargs)[source]¶ Parameters: - required (bool) – boolean flag is this field required
- choices (iterable) – iterable object contains possible values of this field
- validators (list of callable) – the additional validators for field
- default (instance of value_types) – the default value of the field
-
IntField¶
-
class
flyforms.fields.
IntField
(min_value=None, max_value=None, **kwargs)[source]¶ Reflects Python integer (
int
)-
__init__
(min_value=None, max_value=None, **kwargs)[source]¶ Parameters: - required (bool) – boolean flag is this field required
- min_value – the minimum valid value
- max_value – the maximum valid value
- choices (iterable) – iterable object contains possible values of this field
- validators (list of callable) – the additional validators for field
- default (instance of value_types) – the default value of the field
-
FloatField¶
-
class
flyforms.fields.
FloatField
(min_value=None, max_value=None, **kwargs)[source]¶ Reflects Python float (
float
)-
__init__
(min_value=None, max_value=None, **kwargs)¶ Parameters: - required (bool) – boolean flag is this field required
- min_value – the minimum valid value
- max_value – the maximum valid value
- choices (iterable) – iterable object contains possible values of this field
- validators (list of callable) – the additional validators for field
- default (instance of value_types) – the default value of the field
-
Ip4Field¶
-
class
flyforms.fields.
Ip4Field
(**kwargs)[source]¶ Reflects Python string corresponding to an IPv4 address
-
__init__
(**kwargs)[source]¶ Parameters: - required (bool) – boolean flag is this field required
- choices (iterable) – iterable object contains possible values of this field
- validators (list of callable) – the additional validators for field
- default (instance of value_types) – the default value of the field
-
Schema Field¶
Schema Fields is a set of rules to validation data structures such as lists, dicts.
ListField¶
-
class
flyforms.fields.
ListField
(min_length=None, max_length=None, jsonify=True, **kwargs)[source]¶ Reflects iterable Python objects
-
__init__
(min_length=None, max_length=None, jsonify=True, **kwargs)[source]¶ Parameters: - min_length – minimum iterable length
- max_length – maximum iterable length
- jsonify – if passed
item_type
should be one ofjsonify_types
- kwargs – basic
Field
parameters
-
ArrayField¶
Usage¶
# coding=utf-8
from flyforms import *
class CommentForm(Form):
login = StringField()
comment = StringField(max_length=256)
tags = ArrayField(item_type=str)
if __name__ == '__main__':
f = CommentForm(
login="YourLogin",
comment="Your comment",
tags=["schema", "python", "json"] # <-- list
)
print(f.is_bound) # >>> True
print(f.is_valid) # >>> True
print(f.errors) # >>> {}
print(f.data)
# Given list was wrapped into tuple
print(type(f.tags)) # >>> <type 'tuple'>
Custom Fields¶
Sometimes, it is necessary to design custom fields for validation of some special data structures.
If you want do this, you should design your custom subclass of the Field
.
# coding=utf-8
from flyforms.fields import StringField
from flyforms.validators import RegexValidator
class HexField(StringField):
"""
Reflects hex colors
"""
def __init__(self, **kwargs):
super(HexField, self).__init__(**kwargs) # do not forget to call superclass constructor
self.base_validators.append(RegexValidator(regex="^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"))
if __name__ == '__main__':
field = HexField()
print field.is_valid("#fff") # >>> True
print field.is_valid("#fffaa") # >>> False
print field.is_valid("#fffaaa") # >>> True
print field.is_valid("fffaaa") # >>> False
Validators¶
Validators validate given value via their internal logic. If value is invalid ValidationError
will be raised.
ValidationError¶
Builtin validators¶
RequiredValidator¶
TypedValidator¶
EntryValidator¶
MinValueValidator¶
MaxValueValidator¶
MinLengthValidator¶
MaxLengthValidator¶
RegexValidator¶
EmailValidator¶
Ip4AddressValidator¶
ItemTypedValidator¶
JsonItemTypedValidator¶
-
class
flyforms.validators.
JsonItemTypedValidator
[source]¶ Validates is all items from iterable instance of
jsonify_types
Custom Validators¶
If you need to make additional data validation you can use your custom validators.
There is one requirement: validator should be an initialized and callable object.
If you want, you can use and extend one of this classes: Validator
or SimpleValidator
.
Common module¶
This module contains frequently used in FlyForms constants and classes
-
flyforms.common.
UNSET
¶ Frequently used constant, it is a reflection of unidentified values
-
flyforms.common.
jsonify_types
¶ Supported types for JSON encoding and decoding operations
-
class
flyforms.common.
FrozenDict
(*args, **kwargs)[source]¶ Immutable dictionary implementation stolen from StackOverflow