formalize.core module API documention

Form processing/validation module.

See docs/index.rst for full documentation.

class formalize.core.FormValidator(source=None, unpacker=<formalize.unpack.Unpacker object at 0x80891c410>, empty_values_undefined=False)

A specialism of Validator for processing HTTP forms. An Unpacker object will pre-process the data to arrange multi-valued lists into hierarchical data structures.

empty_values_undefined = False

HTML forms do not distinguish between no value entered and an empty string. If empty_values_undefined is True, empty values are treated as undefined. Otherwise they are treated as empty strings.

process(ob, context=None)

Return processed data from source ob.

If this is called as a subvalidator, context should contain the validation context.

unpacker = <formalize.unpack.Unpacker object at 0x80891c410>

The unpacker object to use. See formalize.unpack

class formalize.core.DictValidator(source=None, default=Undefined, message=None, required=True)

Validator for processing dictionary-like data structures

class formalize.core.BaseValidator(source=None, default=Undefined, message=None, required=True)

Base validator class, from which other Validators are derived.

To validate HTML form submissions you will want to use FormValidator. To validate other data structures you will need to use DictValidator, ListValidator, and the other subtypes of BaseValidator that represent primitive types, or own subclasses of BaseValidator.

Validator objects take an input value [typically from a web form] and process it through multiple stages, resulting in either a processed, valid python object being returned, or a ValidationError being raised.

  1. process_prefilters applies any prefilters (see addprefilter). These should do any necessary preprocessing of the raw input.
  2. process_main calls the from_source method to perform the type conversion.
  3. Additional subvalidation checks are performed (see add). These operate on the python object, so can perform tasks such as checking values are within given numerical ranges etc.

At any stage, a ValidationError may be raised. In this event no further processing of the value will be done.

add(*validators)

Add subvalidators to this validator.

addprefilter(func)

Add a prefilter to this validator.

copy(**kwargs)

Return a copy of the validator. If keyword arguments are specified, they will be taken as fields to add to the copy:

>>> from formalize import Unicode
>>> v = DictValidator()(firstname=Unicode())
>>> v2 = v.copy(surname=Unicode())
>>>
>>> v.process({'firstname': 'fred'})
{'firstname': u'fred'}
>>> v2.process({'firstname': 'fred'})
Traceback (most recent call last):
    ...
ValidationError: ValidationError([('surname', u'Value empty or invalid')])
from_source(ob)

Given source object ob (probably a string) return a python object of the destination type.

message

message property getter.

Recursively calls parent validator’s _get_message method. use_default flag is used to ensure that only the first call to self.message will return default_message if no instance-level message is found.

process(value, context=None)

Main entry point for type conversion and validation.

process_main(value, context)

Handle the main conversion and validation stage of processing

process_prefilters(value, context)

Handle the prefilter stage of processing

process_subvalidators(value, context)

Handle the subvalidation stage of processing

register(parent)

Register the validator as belonging to context parent.

required_message

required_message property getter

Recursively calls parent validator’s _get_message method. use_default flag is used to ensure that only the first call to self.required_message will return default_message if no instance-level message is found.

class formalize.core.ListValidator(itemtype, source=None)

Applies a type conversion and validation to a list of values.

Synopsis:

>>> from formalize.core import FormValidator
>>> from formalize.types import Int
>>> v = FormValidator()(
...     a = ListValidator(Int())
... )
>>> v.process({'a' : ['1', '2', '-39']})
{'a': [1, 2, -39]}

See formalize.core.list_transform for a way to transform multiple HTTP form-fields submissions into lists.

class formalize.core.Using(*source_fields)

Using instances wrap other validators to cause them to be called with an arbitrary values pulled from the parent validator.

Example:

>>> from formalize import FormValidator, Unicode, Using
>>> from formalize.checks import assert_true
>>> def check_password(p1, p2, message=u"Passwords do not match"):
...     assert_true(p1 == p2, message)
...     return p1
...
>>> v = FormValidator()(
...     p1=Unicode(),
...     p2=Unicode()(Using('p1', 'p2')(check_password))
... )
>>> v.process({'p1': 'shoe', 'p2': 'gnu'})
Traceback (most recent call last):
...
ValidationError: ValidationError([('p2', u'Passwords do not match')])
class formalize.core.Group(source_fields, message=None, default=Undefined, required=True, propagate_source_errors=False)

Group validators take a number of fields and group them together into a single value.

The constructor takes the following parameters:

  • Source fields (as a tuple/list), eg (date_y, date_m, date_d)
  • Individual keyword arguments to specify validators for the source fields, as per DictValidator, eg date_y=Int(), date_m=Int(), date_d=Int()

The required and default parameters are ignored in this validator type, specify these on the source fields as desired.

add(*args, **kwargs)

Add subvalidators, which act on the grouped value, and fieldvalidators which act on the source field values.

All validator keyword arguments and positional arguments with a non-None source attribute are treated as fieldvalidators. Positional arguments with source left as None are treated as subvalidators.

process_subvalidators(value, context)

Return processed input data from value or raise a ValidationError

register(parent)

Register the validator as belonging to content parent, with fieldname fieldname.

class formalize.core.Any(*subvalidators, **kwargs)

Raise a ValidationError unless at least one of the subvalidators passes.

Example:

>>> from formalize.types import Int
>>> from formalize.checks import lessthan, greaterthan
>>> v = FormValidator()(
...     a=Int()(
...         Any(
...             lessthan(3),
...             greaterthan(7),
...             message=u"Must be less than 3 or greater than 7"
...         )
...     )
... )
>>> v.process({'a': 2})
{'a': 2}
>>> v.process({'a': 8})
{'a': 8}
>>> v.process({'a': 5})
Traceback (most recent call last):
    ...
ValidationError: ValidationError([('a', u'Must be less than 3 or greater than 7')])
register(parent)

Register the validator as belonging to content parent, with fieldname fieldname.

class formalize.core.When(*tests, **kwtests)

When instances can be used to apply validation rules conditionally and may also be passed to the Case constructor as part of a When(...) ... Otherwise(...) series.

class formalize.core.Case(*cases)

When objects work in the context of MappingValidator objects, conditionally applying validation rules.

class formalize.core.Otherwise

Otherwise instances can be passed to the Case constructor as part of a When(...) ... Otherwise(...) series.

Previous topic

Formalize documentation contents

Next topic

formalize.types module API documention

This Page