API Reference

Instance

class umongo.instance.BaseInstance(templates=())[source]

Base class for instance.

Instances aims at collecting and implementing umongo.template.Template:

# Doc is a template, cannot use it for the moment
class Doc(DocumentTemplate):
    pass

instance = Instance()
# doc_cls is the instance's implementation of Doc
doc_cls = instance.register(Doc)
# Implementations are registered as attribute into the instance
instance.Doc is doc_cls
# Now we can work with the implementations
doc_cls.find()

Note

Instance registration is divided between umongo.Document and umongo.EmbeddedDocument.

db

Database used within the instance.

register(template, as_attribute=True)[source]

Generate an umongo.template.Implementation from the given umongo.template.Template for this instance.

Parameters:
  • templateumongo.template.Template to implement
  • as_attribute – Make the generated umongo.template.Implementation available as this instance’s attribute.
Returns:

The umongo.template.Implementation generated

Note

This method can be used as a decorator. This is useful when you only have a single instance to work with to directly use the class you defined:

@instance.register
class MyEmbedded(EmbeddedDocument):
    pass

@instance.register
class MyDoc(Document):
    emb = fields.EmbeddedField(MyEmbedded)

MyDoc.find()
retrieve_document(name_or_template)[source]

Retrieve a umongo.document.DocumentImplementation registered into this instance from it name or it template class (i.e. umongo.Document).

retrieve_embedded_document(name_or_template)[source]

Retrieve a umongo.embedded_document.EmbeddedDocumentImplementation registered into this instance from it name or it template class (i.e. umongo.EmbeddedDocument).

class umongo.Instance(db, templates=())[source]

Automatically configured instance according to the type of the provided database.

class umongo.instance.LazyLoaderInstance(templates=())[source]

Base class for instance with database lazy loading.

Note

This class should not be used directly but instead overloaded. See umongo.PyMongoInstance for example.

db

Database used within the instance.

init(db)[source]

Set the database to use whithin this instance.

Note

The documents registered in the instance cannot be used before this function is called.

class umongo.PyMongoInstance(*args, **kwargs)[source]

umongo.instance.LazyLoaderInstance implementation for pymongo

class umongo.TxMongoInstance(*args, **kwargs)[source]

umongo.instance.LazyLoaderInstance implementation for txmongo

class umongo.MotorAsyncIOInstance(*args, **kwargs)[source]

umongo.instance.LazyLoaderInstance implementation for motor-asyncio

class umongo.MongoMockInstance(*args, **kwargs)[source]

umongo.instance.LazyLoaderInstance implementation for mongomock

Document

umongo.Document

Shortcut to DocumentTemplate

alias of umongo.document.DocumentTemplate

class umongo.document.DocumentTemplate(*args, **kwargs)[source]

Base class to define a umongo document.

Note

Once defined, this class must be registered inside a umongo.instance.BaseInstance to obtain it corresponding umongo.document.DocumentImplementation.

Note

You can provide marshmallow tags (e.g. marshmallow.pre_load or marshmallow.post_dump) to this class that will be passed to the marshmallow schema internally used for this document.

class umongo.document.DocumentOpts(instance, template, collection_name=None, abstract=False, allow_inheritance=None, indexes=None, is_child=True, strict=True, offspring=None)[source]

Configuration for a document.

Should be passed as a Meta class to the Document

@instance.register
class Doc(Document):
    class Meta:
        abstract = True

assert Doc.opts.abstract == True
attribute configurable in Meta description
template no Origine template of the Document
instance no Implementation’s instance
abstract yes Document has no collection and can only be inherited
allow_inheritance yes Allow the document to be subclassed
collection_name yes Name of the collection to store the document into
is_child no Document inherit of a non-abstract document
strict yes Don’t accept unknown fields from mongo (default: True)
indexes yes List of custom indexes
offspring no List of Documents inheriting this one
class umongo.document.DocumentImplementation(**kwargs)[source]

Represent a document once it has been implemented inside a umongo.instance.BaseInstance.

Note

This class should not be used directly, it should be inherited by concrete implementations such as umongo.frameworks.pymongo.PyMongoDocument

classmethod build_from_mongo(data, partial=False, use_cls=False)[source]

Create a document instance from MongoDB data

Parameters:
  • data – data as retrieved from MongoDB
  • use_cls – if the data contains a _cls field, use it determine the Document class to instanciate
clear_modified()[source]

Reset the list of document’s modified items.

collection

Return the collection used by this document class

dbref

Return a pymongo DBRef instance related to the document

dump()[source]

Dump the document.

from_mongo(data, partial=False)[source]

Update the document with the MongoDB data

Parameters:data – data as retrieved from MongoDB
is_created

Return True if the document has been commited to database

is_modified()[source]

Returns True if and only if the document was modified since last commit.

pk

Return the document’s primary key (i.e. _id in mongo notation) or None if not available yet

Warning

Use is_created field instead to test if the document has already been commited to database given _id field could be generated before insertion

post_delete(ret)[source]

Overload this method to get a callback after document deletion. :param ret: Pymongo response sent by the database.

Note

If you use an async driver, this callback can return a defer/future.

post_insert(ret)[source]

Overload this method to get a callback after document insertion. :param ret: Pymongo response sent by the database.

Note

If you use an async driver, this callback can return a defer/future.

post_update(ret)[source]

Overload this method to get a callback after document update. :param ret: Pymongo response sent by the database.

Note

If you use an async driver, this callback can return a defer/future.

pre_delete()[source]

Overload this method to get a callback before document deletion. :return: Additional filters dict that will be used for the query to

select the document to update.

Note

If you use an async driver, this callback can return a defer/future.

pre_insert()[source]

Overload this method to get a callback before document insertion.

Note

If you use an async driver, this callback can return a defer/future.

pre_update()[source]

Overload this method to get a callback before document update. :return: Additional filters dict that will be used for the query to

select the document to update.

Note

If you use an async driver, this callback can return a defer/future.

to_mongo(update=False)[source]

Return the document as a dict compatible with MongoDB driver.

Parameters:update – if True the return dict should be used as an update payload instead of containing the entire document
update(data)[source]

Update the document with the given data.

Abstracts

class umongo.abstract.BaseSchema(only=None, exclude=(), prefix='', many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None)[source]

All schema used in umongo should inherit from this base schema

as_marshmallow_schema(params=None, base_schema_cls=<class 'marshmallow.schema.Schema'>, check_unknown_fields=True, mongo_world=False)[source]

Return a pure-marshmallow version of this schema class.

Parameters:
  • params – Per-field dict to pass parameters to their field creation.
  • base_schema_cls – Class the schema will inherit from ( default: marshmallow.Schema).
  • check_unknown_fields – Unknown fields are considered as errors (default: True).
  • mongo_world – If True the schema will work against the mongo world instead of the OO world (default: False).
map_to_field(func)[source]

Apply a function to every field in the schema

>>> def func(mongo_path, path, field):
...     pass
class umongo.abstract.BaseField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]

All fields used in umongo should inherit from this base field.

Enabled flags resulting index
<no flags>  
allow_none  
required  
required, allow_none  
required, unique, allow_none unique
unique unique, sparse
unique, required unique
unique, allow_none unique, sparse

Note

Even with allow_none flag, the unique flag will refuse duplicated

null value (consider unsetting the field with del instead)

as_marshmallow_field(params=None, mongo_world=False)[source]

Return a pure-marshmallow version of this field.

Parameters:
  • params – Additional parameters passed to the marshmallow field class constructor.
  • mongo_world – If True the field will work against the mongo world instead of the OO world (default: False)
default_error_messages = {'unique': 'Field value must be unique.', 'unique_compound': 'Values of fields {fields} must be unique together.'}
deserialize(value, attr=None, data=None)[source]

Deserialize value.

Raises:ValidationError – If an invalid value is passed or if a required value is missing.
deserialize_from_mongo(value)[source]
serialize(attr, obj, accessor=None)[source]

Pulls the value for the given key from the object, applies the field’s formatting and returns the result.

Parameters:
  • attr (str) – The attribute or key to get from the object.
  • obj (str) – The object to pull the key from.
  • accessor (callable) – Function used to pull values from obj.
Raises:

ValidationError – In case of formatting problem

serialize_to_mongo(obj)[source]
translate_query(key, query)[source]
class umongo.abstract.BaseValidator(*args, **kwargs)[source]

All validators in umongo should inherit from this base validator.

class umongo.abstract.BaseDataObject[source]

All data objects in umongo should inherit from this base data object.

classmethod build_from_mongo(data)[source]
clear_modified()[source]
dump()[source]
from_mongo(data)[source]
is_modified()[source]
to_mongo(update=False)[source]

Fields

class umongo.fields.DictField(*args, **kwargs)[source]
translate_query(key, query)[source]
class umongo.fields.ListField(*args, **kwargs)[source]
as_marshmallow_field(params=None, mongo_world=False)[source]

Return a pure-marshmallow version of this field.

Parameters:
  • params – Additional parameters passed to the marshmallow field class constructor.
  • mongo_world – If True the field will work against the mongo world instead of the OO world (default: False)
map_to_field(mongo_path, path, func)[source]

Apply a function to every field in the schema

class umongo.fields.StringField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.UUIDField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.NumberField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.IntegerField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.DecimalField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.BooleanField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.FormattedStringField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.FloatField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.DateTimeField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.UrlField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
umongo.fields.URLField

alias of umongo.fields.UrlField

class umongo.fields.EmailField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
umongo.fields.StrField

alias of umongo.fields.StringField

umongo.fields.BoolField

alias of umongo.fields.BooleanField

umongo.fields.IntField

alias of umongo.fields.IntegerField

class umongo.fields.ConstantField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.StrictDateTimeField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.ObjectIdField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.ReferenceField(document, *args, reference_cls=<class 'umongo.data_objects.Reference'>, **kwargs)[source]
as_marshmallow_field(params=None, mongo_world=False)[source]

Return a pure-marshmallow version of this field.

Parameters:
  • params – Additional parameters passed to the marshmallow field class constructor.
  • mongo_world – If True the field will work against the mongo world instead of the OO world (default: False)
document_cls

Return the instance’s umongo.embedded_document.DocumentImplementation implementing the document attribute.

class umongo.fields.GenericReferenceField(*args, reference_cls=<class 'umongo.data_objects.Reference'>, **kwargs)[source]
as_marshmallow_field(params=None, mongo_world=False)[source]

Return a pure-marshmallow version of this field.

Parameters:
  • params – Additional parameters passed to the marshmallow field class constructor.
  • mongo_world – If True the field will work against the mongo world instead of the OO world (default: False)
class umongo.fields.EmbeddedField(embedded_document, *args, **kwargs)[source]
as_marshmallow_field(params=None, mongo_world=False)[source]

Return a pure-marshmallow version of this field.

Parameters:
  • params – Additional parameters passed to the marshmallow field class constructor.
  • mongo_world – If True the field will work against the mongo world instead of the OO world (default: False)
embedded_document_cls

Return the instance’s umongo.embedded_document.EmbeddedDocumentImplementation implementing the embedded_document attribute.

map_to_field(mongo_path, path, func)[source]

Apply a function to every field in the schema

nested

Data objects

class umongo.data_objects.List(container_field, *args, **kwargs)[source]
append(object) → None -- append object to end[source]
clear() → None -- remove all items from L[source]
clear_modified()[source]
container_field
extend(iterable) → None -- extend list by appending elements from the iterable[source]
is_modified()[source]
pop([index]) → item -- remove and return item at index (default last).[source]

Raises IndexError if list is empty or index is out of range.

remove(value) → None -- remove first occurrence of value.[source]

Raises ValueError if the value is not present.

reverse(*args, **kwargs)[source]

L.reverse() – reverse IN PLACE

set_modified()[source]
sort(key=None, reverse=False) → None -- stable sort *IN PLACE*[source]
class umongo.data_objects.Dict(*args, **kwargs)[source]
clear_modified()[source]
is_modified()[source]
set_modified()[source]
class umongo.data_objects.Reference(document_cls, pk)[source]
error_messages = {'not_found': 'Reference not found for document {document}.'}
fetch(no_data=False, force_reload=False)[source]

Retrieve from the database the referenced document

Parameters:
  • no_data – if True, the caller is only interested in whether or not the document is present in database. This means the implementation may not retrieve document’s data to save bandwidth.
  • force_reload – if True, ignore any cached data and reload referenced document from database.

Marshmallow integration

umongo.marshmallow_bonus.schema_validator_check_unknown_fields(self, data, original_data)[source]

Schema validator, raise ValidationError for unknown fields in a marshmallow schema.

example:

class MySchema(marshsmallow.Schema):
    # method's name is not important
    __check_unknown_fields = validates_schema(pass_original=True)(
        schema_validator_check_unknown_fields)

    # Define the rest of your schema
    ...

..note:: Unknown fields with missing value will be ignored

umongo.marshmallow_bonus.schema_from_umongo_get_attribute(self, attr, obj, default)[source]
Overwrite default Schema.get_attribute method by this one to access
umongo missing fields instead of returning None.

example:

class MySchema(marshsmallow.Schema):
    get_attribute = schema_from_umongo_get_attribute

    # Define the rest of your schema
    ...
class umongo.marshmallow_bonus.SchemaFromUmongo(only=None, exclude=(), prefix='', many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None)[source]

Custom marshmallow.Schema subclass providing unknown fields checking and custom get_attribute for umongo documents.

get_attribute(attr, obj, default)
Overwrite default Schema.get_attribute method by this one to access
umongo missing fields instead of returning None.

example:

class MySchema(marshsmallow.Schema):
    get_attribute = schema_from_umongo_get_attribute

    # Define the rest of your schema
    ...
class umongo.marshmallow_bonus.StrictDateTime(load_as_tz_aware=False, *args, **kwargs)[source]

Marshmallow DateTime field with extra parameter to control whether dates should be loaded as tz_aware or not

class umongo.marshmallow_bonus.ObjectId(default=<marshmallow.missing>, attribute=None, data_key=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Marshmallow field for bson.ObjectId

class umongo.marshmallow_bonus.Reference(*args, mongo_world=False, **kwargs)[source]

Marshmallow field for umongo.fields.ReferenceField

class umongo.marshmallow_bonus.GenericReference(*args, mongo_world=False, **kwargs)[source]

Marshmallow field for umongo.fields.GenericReferenceField

Exceptions

exception umongo.exceptions.AbstractDocumentError[source]
exception umongo.exceptions.AlreadyRegisteredDocumentError[source]
exception umongo.exceptions.BuilderNotDefinedError[source]
exception umongo.exceptions.DeleteError[source]
exception umongo.exceptions.DocumentDefinitionError[source]
exception umongo.exceptions.FieldNotLoadedError[source]
exception umongo.exceptions.MissingSchemaError[source]
exception umongo.exceptions.NoCollectionDefinedError[source]
exception umongo.exceptions.NoCompatibleBuilderError[source]
exception umongo.exceptions.NoDBDefinedError[source]
exception umongo.exceptions.NotCreatedError[source]
exception umongo.exceptions.NotRegisteredDocumentError[source]
exception umongo.exceptions.UMongoError[source]
exception umongo.exceptions.UnknownFieldInDBError[source]
exception umongo.exceptions.UpdateError[source]