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(**data)[source]

The root class for all Forms

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 receive UNSET value

Properties

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.

data

Deprecated since version 0.3.0: Will be removed in v1.0.0. Use Form.to_python() instead

Returns dict with bound data (if you need all data even UNSET values - use raw_data)

Attributes

raw_data

Normal Python dict contains all Form data (even UNSET values)

_fields

Python set contains all defined fields names

Methods

to_python()[source]

Returns dict with bound data (if you need all data even UNSET values - use raw_data)

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

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.

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 not Form subclass

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

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(required=True, choices=(), validators=(), **kwargs)[source]

This the base class for all Fields. Fields instances reflect and validate data.

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 example list) it’ll be converted to immutable (for example tuple)

Parameters:
  • value – the value to bind
  • name (str) – field name (optional)
Returns:

given value or field.default if value is UNSET

New in version 0.2.0.

Attributes

required

Boolean flag passed to constructor

default

The default value for Field (passed to constructor value or UNSET)

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 and custom_validators

Basic Fields

StringField

class flyforms.fields.StringField(min_length=None, max_length=None, regex='', **kwargs)[source]

Reflects Python strings

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

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)

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)

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

BooleanField

class flyforms.fields.BooleanField(**kwargs)[source]

Reflects Python boolean (bool)

Parameters:
  • required (bool) – boolean flag is this field required
  • 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

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

DatetimeField

class flyforms.fields.DatetimeField(required=True, fmt='%Y-%m-%d %H:%M:%S', now=False)[source]

New in version 0.3.0.

A datetime field.

Parse string contains datetime via datetime.strptime

Parameters:
  • fmt (str) – datetime format
  • now (bool) – if passed the default value will be datetime.now()

New in version 0.3.0.

Schema Field

Schema Fields is a set of rules to validation data structures such as lists, dicts.

ListField

API

class flyforms.fields.ListField(min_length=None, max_length=None, jsonify=True, **kwargs)[source]

Reflects iterable Python objects

Parameters:
  • required (bool) – boolean flag is this field required or can be empty
  • min_length (int) – minimum iterable length
  • max_length (int) – maximum iterable length
  • jsonify (bool) – if passed item_type should be one of jsonify_types
  • validators (list of callable) – the additional validators for field
  • default (instance of value_types) – the default value of the field

New in version 0.2.0.

Usage

# coding=utf-8
from flyforms import Form, ListField, UNSET


class ListForm(Form):
    jsonify_list = ListField(min_length=2, max_length=5)
    common_list = ListField(min_length=3, jsonify=False)

if __name__ == '__main__':
    form = ListForm(
        jsonify_list=["Hello!", 2.5, 0],
        common_list=[object(), 500, "... world!", UNSET]
    )

    print(form.is_bound)   # >>> True
    print(form.is_valid)   # >>> True
    print(form.errors)   # >>> {}

ArrayField

API

class flyforms.fields.ArrayField(item_type, jsonify=True, **kwargs)[source]

New in version 0.2.0.

Reflects iterable objects where each item same type

Parameters:
  • item_type – type of each item in the list
  • min_length (int) – minimum iterable length
  • max_length (int) – maximum iterable length
  • jsonify (bool) – if passed item_type should be one of jsonify_types
  • required (bool) – boolean flag is this field required or can be empty
  • validators (list of callable) – the additional validators for field
  • default (instance of value_types) – the default value of the field

Usage

# ArrayField usage
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'>

DictField

API

class flyforms.fields.DictField(schema, **kwargs)[source]

New in version 0.3.0.

Reflects Python dict

Parameters:
  • schema (dict) – template to dict validation
  • required (bool) – boolean flag is this field required or can be empty
  • validators (list of callable) – the additional validators for field
  • default (instance of value_types) – the default value of the field

Usage

# DictField usage
from flyforms import *


class MyForm(Form):
    cred = DictField(
        schema={
            "email": EmailField(),
            "password": StringField(
                min_length=8,
                regex=r"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])",
                max_length=64
            )
        }
    )


if __name__ == '__main__':
    f = MyForm(
        cred={
            "email": "qwerty@gmail.com",
            "password": "Qwerty_#123"
        }  # <--- dict
    )

    print(f.is_valid)  # >>> True
    print(f.is_bound)  # >>> True
    print(f.errors)  # >>> {}
    print(f.cred)   # >>> {'password': 'Qwerty_#123', 'email': 'qwerty@gmail.com'}
    print(type(f.cred))  # >>> <class 'flyforms.common.FrozenDict'>  <--- !!!

Embedded DictFields

# DictField nested usage
from flyforms import *


class MyForm(Form):
    field = DictField(
        schema={
            "list_field": ListField(),
            "nested_dict": DictField(
                schema={
                    "field1": EmailField(),
                    "field2": StringField()
                }
            )
        }
    )

if __name__ == '__main__':
    f = MyForm(
        field={
            "list_field": [0, 1, "Hello world!"],
            "nested_dict": {
                "field1": "qwerty@qwerty.com",
                "field2": "Hello world!"
            }
        }
    )

    print(f.is_valid)  # >>> True
    print(f.is_bound)  # >>> True
    print(f.errors)  # >>> {}
    print(f.data)

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

class flyforms.validators.ValidationError[source]

Raised when a validator fails to validate it’s input.

Builtin validators

RequiredValidator

class flyforms.validators.RequiredValidator[source]

Validates is given value not UNSET object

TypedValidator

class flyforms.validators.TypedValidator(value_types)[source]

Validates is given value instance of defined value_types

Parameters:value_types – list of possible value types

EntryValidator

class flyforms.validators.EntryValidator(iterable)[source]

Validates is given value in specified during initialization iterable object

Parameters:iterable – the iterable object
Raise:TypeError if given object is not iterable

MinValueValidator

class flyforms.validators.MinValueValidator(min_value, strong=True)[source]

Validates is given value greater than specified during initialization value

Parameters:
  • min_value – the minimum valid value
  • strong (bool) – boolean flag should be comparison strict or not

MaxValueValidator

class flyforms.validators.MaxValueValidator(max_value, strong=True)[source]

Validates is given value less than specified during initialization value

Parameters:
  • max_value – the maximum valid value
  • strong (bool) – boolean flag should be comparison strict or not

MinLengthValidator

class flyforms.validators.MinLengthValidator(min_length, strong=True)[source]

Validates the minimum object length

Parameters:
  • min_length – the minimum valid length
  • strong (bool) – boolean flag should be comparison strict or not

MaxLengthValidator

class flyforms.validators.MaxLengthValidator(max_length, strong=True)[source]

Validates the maximum object length

Parameters:
  • max_length – the maximum valid length
  • strong (bool) – boolean flag should be comparison strict or not

RegexValidator

class flyforms.validators.RegexValidator(regex, flags=0)[source]

Validates matching with regular expression

Parameters:
  • regex – the regular expression
  • flags – flags passed to re.match function

EmailValidator

class flyforms.validators.EmailValidator[source]

Validates an email address via simple regex.

Ip4AddressValidator

class flyforms.validators.Ip4AddressValidator[source]

Validates an IPv4 address via simple regex.

ItemTypedValidator

class flyforms.validators.ItemTypedValidator(item_types)[source]

Validates is all items from iterable instance of defined value_types

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.

Validator class

class flyforms.validators.Validator[source]

This the base class for all Fields.

validate(value)[source]

Validate the given value

Parameters:value – given value to validate
Raises ValidationError:
 if given value is not valid
is_valid(value)[source]

Validate value and catch :py:class`.ValidationError`.

Parameters:value – given value to validate
Returns:True if :py:class`.ValidationError` was not raised, otherwise False
Return type:bool

SimpleValidator class

class flyforms.validators.SimpleValidator[source]

The Validator’s subclass with only one validation case. Given value should satisfies condition in positive_case method

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

flyforms.common.is_set(value)

Checks is given value is not UNSET

class flyforms.common.FrozenDict(*args, **kwargs)[source]

Immutable dictionary implementation stolen from StackOverflow