TODO intro
TODO strict, duck, etc.
If descent_validators is defined, these validators will be run first, before member elements are validated.
If validators is defined, these validators will be run after member elements are validated.
Return a class with name = name
Parameter: | name – a string or None. str will be converted to unicode. |
---|---|
Returns: | a new class |
Return a class with attributes set from **overrides.
Parameter: | **overrides – new values for any attributes already present on the class. A TypeError is raised for unknown attributes. |
---|---|
Returns: | a new class |
Return an element initialized with an object’s attributes.
Parameters: |
|
---|
include and omit are mutually exclusive.
This is a convenience constructor for set_by_object():
element = cls(**kw)
element.set_by_object(obj, include, omit, rename)
One of ‘strict’, ‘subset’ or ‘duck’. Default ‘subset’.
See set() Policy
Bases: flatland.schema.containers.Mapping, dict
A mapping Container with named members.
Return a class with descent validators set to *validators.
Parameter: | *validators – one or more validator functions, replacing any descent validators present on the class. |
---|---|
Returns: | a new class |
Find a child element by string path.
Parameters: |
|
---|---|
Returns: | an Element or raises KeyError. |
>>> first_address = form.el('contact.addresses.0')
>>> first_address.el('street1')
<String u'street1'; value=None>
Given a relative path as above, el() searches for a matching path among the element’s children.
If path begins with sep, the path is considered fully qualified and the search is resolved from the Element.root. The leading sep will always match the root node, regardless of its name.
>>> form.el('.contact.addresses.0.city')
<String u'city'; value=None>
>>> first_address.el('.contact.addresses.0.city')
<String u'city'; value=None>
Find child elements by string path.
Parameters: |
|
---|---|
Returns: | a list of Element instances, an Element if single is true, or raises LookupError. |
>>> cities = form.find('/contact/addresses[:]/city')
>>> [el.value for el in cities]
[u'Kingsport', u'Dunwich']
>>> form.find('/contact/name', single=True)
<String u'name'; value=u'Obed Marsh'>
Export an element hierarchy as a flat sequence of key, value pairs.
Parameters: |
|
---|
Encodes the element hierarchy in a sep-separated name string, paired with any representation of the element you like. The default is the Unicode value of the element, and the output of the default flatten() can be round-tripped with set_flat().
Given a simple form with a string field and a nested dictionary:
>>> from flatland import Dict, String
>>> class Nested(Form):
... contact = Dict.of(String.named(u'name'),
... Dict.named(u'address'). ... of(String.named(u'email')))
...
>>> element = Nested()
>>> element.flatten()
[(u'contact_name', u''), (u'contact_address_email', u'')]
The value of each pair can be customized with the value callable:
>>> element.flatten(value=operator.attrgetter('u'))
[(u'contact_name', u''), (u'contact_address_email', u'')]
>>> element.flatten(value=lambda el: el.value)
[(u'contact_name', None), (u'contact_address_email', None)]
Solo elements will return a sequence containing a single pair:
>>> element['name'].flatten()
[(u'contact_name', u'')]
Return the element’s complete flattened name as a string.
Joins this element’s path with sep and returns the fully qualified, flattened name. Encodes all Container and other structures into a single string.
Example:
>>> import flatland
>>> form = flatland.List('addresses',
... flatland.String('address'))
>>> element = form()
>>> element.set([u'uptown', u'downtown'])
>>> element.el('0').value
u'uptown'
>>> element.el('0').flattened_name()
u'addresses_0_address'
Return the fully qualified path name of the element.
Returns a sep-separated string of el() compatible element indexes starting from the Element.root (.) down to the element.
>>> from flatland import Dict, Integer
>>> Point = Dict.named(u'point').of(Integer.named(u'x'),
... Integer.named(u'y'))
>>> p = Point(dict(x=10, y=20))
>>> p.name
u'point'
>>> p.fq_name()
u'.'
>>> p['x'].name
u'x'
>>> p['x'].fq_name()
u'.x'
The index used in a path may not be the name of the element. For example, sequence members are referenced by their numeric index.
>>> from flatland import List, String
>>> Addresses = List.named('addresses').of(String.named('address'))
>>> form = Addresses([u'uptown', u'downtown'])
>>> form.name
u'addresses'
>>> form.fq_name()
u'.'
>>> form[0].name
u'address'
>>> form[0].fq_name()
u'.0'
Return a class with additional descent *validators.
Parameters: |
|
---|---|
Returns: | a new class |
Return a class with additional *validators.
Parameters: |
|
---|---|
Returns: | a new class |
Set fields with an object’s attributes.
Parameters: |
|
---|
include and omit are mutually exclusive.
Sets fields on self, using as many attributes as possible from obj. Object attributes that do not correspond to field names are ignored.
Mapping instances have two corresponding methods useful for round-tripping values in and out of your domain objects.
update_object() performs the inverse of set_object(), and slice() is useful for constructing new objects.
>>> user = User('biff', 'secret')
>>> form = UserForm()
>>> form.set_by_object(user)
>>> form['login'].value
u'biff'
>>> form['password'] = u'new-password'
>>> form.update_object(user, omit=['verify_password'])
>>> user.password
u'new-password'
>>> user_keywords = form.slice(omit=['verify_password'], key=str)
>>> sorted(user_keywords.keys())
['login', 'password']
>>> new_user = User(**user_keywords)
Set element values from pairs, expanding the element tree as needed.
Given a sequence of name/value tuples or a dict, build out a structured tree of value elements.
Update an object’s attributes using the element’s values.
Produces a slice() using include, omit, rename and key, and sets the selected attributes on obj using setattr.
Returns: | nothing. obj is modified directly. |
---|
Assess the validity of this element and its children.
Parameters: |
|
---|
Iterates through this element and all of its children, invoking each element’s schema.validate_element(). Each element will be visited twice: once heading down the tree, breadth-first, and again heading back up in reverse order.
Returns True if all validations pass, False if one or more fail.
Validates on the first (downward) and second (upward) pass.
If descent_validators are defined on the schema, they will be evaluated before children are validated. If a validation function returns flatland.SkipAll or flatland.SkipFalse, downward validation will halt on this container and children will not be validated.
If validators are defined, they will be evaluated after children are validated.
See FieldSchema.validate_element().
Return a class with validators set to *validators.
Parameter: | *validators – one or more validator functions, replacing any validators present on the class. |
---|---|
Returns: | a new class |
A calculated “default” value.
If default_factory is present, it will be called with the element as a single positional argument. The result of the call will be returned.
Otherwise, returns default.
When comparing an element’s value to its default value, use this property in the comparison.
Bases: flatland.schema.containers.Dict
A Mapping which may contain a subset of the schema’s allowed keys.
This differs from Dict in that new instances are not created with empty values for all possible keys. In addition, mutating operations are allowed so long as the operations operate within the schema. For example, you may pop() and del members of the mapping.
The subset of fields to autovivify on instantiation.
May be None or 'required'. If None, mappings will be created empty and mutation operations are unrestricted within the bounds of the field_schema. If required, fields with optional of False will always be present after instantiation, and attempts to remove them from the mapping with del and friends will raise TypeError.