API reference

Validation

exception monk.validation.MissingKey[source]

Raised when a key is defined in the structure spec but is missing from a data dictionary.

exception monk.validation.StructureSpecificationError[source]

Raised when malformed document structure is detected.

exception monk.validation.UnknownKey[source]

Raised when a key in data dictionary is missing from the corresponding structure spec.

exception monk.validation.ValidationError[source]

Raised when a document or its part cannot pass validation.

monk.validation.validate_structure(spec, data, skip_missing=False, skip_unknown=False)[source]

Validates given document against given structure specification. Always returns None.

Parameters:
  • specdict; document structure specification.
  • datadict; document to be validated against the spec.
  • skip_missingbool; if True, MissingKey is never raised. Default is False.
  • skip_unknownbool; if True, UnknownKey is never raised. Default is False.

Can raise:

MissingKey
if a key is in spec but not in data.
UnknownKey
if a key is in data but not in spec.
StructureSpecificationError
if errors were found in spec.
TypeError
if a value in data does not belong to the designated type.
monk.validation.validate_structure_spec(spec)[source]

Checks whether given document structure specification dictionary if defined correctly.

Raises StructureSpecificationError if the specification is malformed.

Data manipulation

monk.manipulation.VALUE_MERGERS

Default series of mergers:

class monk.manipulation.AnyMerger(spec, value)[source]

Any value from spec that can be checked for type.

class monk.manipulation.DictMerger(spec, value)[source]

Nested dictionary. Example:

>>> DictMerger({'a': 123}, {}).process()
{'a': 123}
>>> DictMerger({'a': 123}, {'a': 456}).process()
{'a': 456}
class monk.manipulation.FuncMerger(spec, value)[source]

Default value is obtained from a function with no arguments. It is expected that the callable does not have side effects. Example:

>>> FuncMerger(lambda: 123, None).process()
123
>>> FuncMerger(lambda: 123, 456).process()
456
class monk.manipulation.ListMerger(spec, value)[source]

Nested list.

class monk.manipulation.TypeMerger(spec, value)[source]

Type definition. Preserves empty values. Example:

>>> TypeMerger(int, None).process()
None
>>> TypeMerger(int, 123).process()
123
class monk.manipulation.ValueMerger(spec, value)[source]

Base class for value mergers.

check()[source]

Returns True if this merger can handle given spec/value pair, otherwise returns False.

Subclasses must overload this method.

process()[source]

Returns a merged version or self.spec and self.value.

Subclasses must overload this method.

monk.manipulation.merge_value(spec, value, mergers)[source]

Returns a merged value based on given spec and data, using given sequence of mergers.

The mergers are polled expected to be subclasses of ValueMerger. They are polled one by one; the first one that agrees to process given value is used to produce the result.

Example:

>>> merge_value({'a': 123}, {}, [DictMerger])
{'a': 123}
>>> merge_value({'a': 123}, {'a': 456}, [DictMerger])
{'a': 456}
monk.manipulation.merged(spec, data, value_processor=None, mergers=(<class 'monk.manipulation.TypeMerger'>, <class 'monk.manipulation.DictMerger'>, <class 'monk.manipulation.ListMerger'>, <class 'monk.manipulation.FuncMerger'>, <class 'monk.manipulation.AnyMerger'>))[source]

Returns a dictionary based on spec + data.

Does not validate values. If data overrides a default value, it is trusted. The result can be validated later with validate_structure().

Note that a key/value pair is added from spec either if data does not define this key at all, or if the value is None. This behaviour may not be suitable for all cases and therefore may change in the future.

You can fine-tune the process by changing the list of mergers.

Parameters:
  • specdict. A document structure specification.
  • datadict. Overrides some or all default values from the spec.
  • value_processor – function, must take one argument and return the modified value.
  • mergerstuple. An ordered series of ValueMerger subclasses. Default is VALUE_MERGERS. The mergers are passed to merge_value().

Models

Declaring indexes

Let’s declare a model with indexes:

class Item(Document):
    structure = dict(text=unicode, slug=unicode)
    indexes = dict(text=None, slug=dict(unique=True))

Now create a model instance:

item = Item(text=u'foo', slug=u'bar')

Save it and make sure the indexes are created:

item.save(db)

The last line is roughly equivalent to:

collection = db[item.collection]
collection.ensure_index('text')
collection.ensure_index('slug', unique=True)
collection.save(dict(item))  # also validation, transformation, etc.
class monk.modeling.Document(*args, **kwargs)[source]

A structured dictionary that is bound to MongoDB and supports dot notation for access to items.

Inherits features from:

class monk.modeling.DotExpandedDictMixin[source]

Makes the dictionary dot-expandable by exposing dictionary members via __getattr__ and __setattr__ in addition to __getitem__ and __setitem__. For example, this is the default API:

data = {'foo': {'bar': 0 } }
print data['foo']['bar']
data['foo']['bar'] = 123

This mixin adds the following API:

print data.foo.bar
data.foo.bar = 123

Nested dictionaries are converted to dot-expanded ones on adding.

class monk.modeling.MongoBoundDictMixin[source]

Adds MongoDB-specific features to the dictionary.

collection

Collection name.

indexes

(TODO)

classmethod find(db, *args, **kwargs)[source]

Returns a MongoResultSet object.

Example:

items = Item.find(db, {'title': u'Hello'})

Note

The arguments are those of pymongo collection’s find method. A frequent error is to pass query key/value pairs as keyword arguments. This is wrong. In most cases you will want to pass a dictionary (“query spec”) as the first positional argument.

get_id()[source]

Returns object id or None.

classmethod get_one(db, *args, **kwargs)[source]

Returns an object that corresponds to given query or None.

Example:

item = Item.get_one(db, {'title': u'Hello'})
get_ref()[source]

Returns a DBRef for this object or None.

save(db)[source]

Saves the object to given database. Usage:

item = Item(title=u'Hello')
item.save(db)

Collection name is taken from MongoBoundDictMixin.collection.

class monk.modeling.StructuredDictMixin[source]

A dictionary with structure specification and validation.

structure

The document structure specification. For details see monk.validation.validate_structure_spec() and monk.validation.validate_structure().

class monk.modeling.TypedDictReprMixin[source]

Makes repr(self) depend on unicode(self).

Table Of Contents

Previous topic

Monk

This Page