API Reference

Instance

class umongo.instance.Instance(db=None)[source]

Abstract instance class

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

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

instance = MyFrameworkInstance()
# 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.

register(template)[source]

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

Parameters:templateumongo.template.Template to implement
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).

set_db(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.frameworks.pymongo.PyMongoInstance(db=None)[source]

umongo.instance.Instance implementation for pymongo

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, 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
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, 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()

Reset the list of document’s modified items.

clone()[source]

Return a copy of this Document as a new Document instance

All fields are deep-copied except the _id field.

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)[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 be asynchronous.

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 be asynchronous.

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 be asynchronous.

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 be asynchronous.

pre_insert()[source]

Overload this method to get a callback before document insertion.

Note

If you use an async driver, this callback can be asynchronous.

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 be asynchronous.

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.

EmbeddedDocument

umongo.EmbeddedDocument

Shortcut to EmbeddedDocumentTemplate

alias of umongo.embedded_document.EmbeddedDocumentTemplate

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

Base class to define a umongo embedded document.

Note

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

class umongo.embedded_document.EmbeddedDocumentOpts(instance, template, abstract=False, is_child=False, strict=True, offspring=None)[source]

Configuration for an umongo.embedded_document.EmbeddedDocument.

Should be passed as a Meta class to the EmbeddedDocument

@instance.register
class MyEmbeddedDoc(EmbeddedDocument):
    class Meta:
        abstract = True

assert MyEmbeddedDoc.opts.abstract == True
attribute configurable in Meta description
template no Origin template of the embedded document
instance no Implementation’s instance
abstract yes Embedded document can only be inherited
is_child no Embedded document inherit of a non-abstract embedded document
strict yes Don’t accept unknown fields from mongo (default: True)
offspring no List of embedded documents inheriting this one
class umongo.embedded_document.EmbeddedDocumentImplementation(**kwargs)[source]

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

classmethod build_from_mongo(data, use_cls=True)[source]

Create an embedded 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 EmbeddedDocument class to instanciate
clear_modified()[source]

Reset the list of document’s modified items.

dump()[source]

Dump the embedded document.

update(data)[source]

Update the embedded document with the given data.

MixinDocument

umongo.MixinDocument

Shortcut to MixinDocumentTemplate

alias of umongo.mixin.MixinDocumentTemplate

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

Base class to define a umongo mixin document.

Note

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

class umongo.mixin.MixinDocumentOpts(instance, template)[source]

Configuration for an umongo.mixin.MixinDocument.

attribute configurable in Meta description
template no Origin template of the embedded document
instance no Implementation’s instance
class umongo.mixin.MixinDocumentImplementation[source]

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

Abstracts

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

All schema used in umongo should inherit from this base schema

MA_BASE_SCHEMA_CLS

alias of BaseMarshmallowSchema

as_marshmallow_schema()[source]

Return a pure-marshmallow version of this schema class

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.

MARSHMALLOW_ARGS_PREFIX = 'marshmallow_'
as_marshmallow_field()[source]

Return a pure-marshmallow version of this field

default_error_messages = {'unique': 'Field value must be unique.', 'unique_compound': 'Values of fields {fields} must be unique together.'}
deserialize_from_mongo(value)[source]
serialize_to_mongo(obj)[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

umongo fields

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.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.NaiveDateTimeField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.AwareDateTimeField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.DateField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]

This field converts a date to a datetime to store it as a BSON Date

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.DictField(*args, **kwargs)[source]
as_marshmallow_field()[source]

Return a pure-marshmallow version of this field

class umongo.fields.ListField(*args, **kwargs)[source]
as_marshmallow_field()[source]

Return a pure-marshmallow version of this field

map_to_field(mongo_path, path, func)[source]

Apply a function to every field in the schema

class umongo.fields.ConstantField(*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]
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]
class umongo.fields.EmbeddedField(embedded_document, *args, **kwargs)[source]
as_marshmallow_field()[source]

Return a pure-marshmallow version of this field

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(inner_field, *args, **kwargs)[source]
append(obj)[source]

Append object to the end of the list.

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

Remove all items from list.

clear_modified()[source]
extend(iterable)[source]

Extend list by appending elements from the iterable.

inner_field
insert(i, obj)[source]

Insert object before index.

is_modified()[source]
pop(*args, **kwargs)[source]

Remove and return item at index (default last).

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

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

Remove first occurrence of value.

Raises ValueError if the value is not present.

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

Reverse IN PLACE.

set_modified()[source]
sort(*args, **kwargs)[source]

Stable sort IN PLACE.

class umongo.data_objects.Dict(key_field, value_field, *args, **kwargs)[source]
clear_modified()[source]
is_modified()[source]
key_field
pop(k[, d]) → v, remove specified key and return the corresponding value.[source]

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a[source]

2-tuple; but raise KeyError if D is empty.

set_modified()[source]
setdefault(key, obj=None)[source]

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) → None. Update D from dict/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

value_field
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

Pure marshmallow fields used in umongo

class umongo.marshmallow_bonus.ObjectId(*, load_default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, dump_default: Any = <marshmallow.missing>, default: Any = <marshmallow.missing>, data_key: Optional[str] = None, attribute: Optional[str] = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]], None] = None, required: bool = False, allow_none: Optional[bool] = None, load_only: bool = False, dump_only: bool = False, error_messages: Optional[Dict[str, str]] = None, metadata: Optional[Mapping[str, Any]] = None, **additional_metadata)[source]

Marshmallow field for bson.objectid.ObjectId

class umongo.marshmallow_bonus.Reference(*, load_default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, dump_default: Any = <marshmallow.missing>, default: Any = <marshmallow.missing>, data_key: Optional[str] = None, attribute: Optional[str] = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]], None] = None, required: bool = False, allow_none: Optional[bool] = None, load_only: bool = False, dump_only: bool = False, error_messages: Optional[Dict[str, str]] = None, metadata: Optional[Mapping[str, Any]] = None, **additional_metadata)[source]

Marshmallow field for umongo.fields.ReferenceField

class umongo.marshmallow_bonus.GenericReference(*, load_default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, dump_default: Any = <marshmallow.missing>, default: Any = <marshmallow.missing>, data_key: Optional[str] = None, attribute: Optional[str] = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]], None] = None, required: bool = False, allow_none: Optional[bool] = None, load_only: bool = False, dump_only: bool = False, error_messages: Optional[Dict[str, str]] = None, metadata: Optional[Mapping[str, Any]] = None, **additional_metadata)[source]

Marshmallow field for umongo.fields.GenericReferenceField

Exceptions

umongo exceptions

exception umongo.exceptions.AbstractDocumentError[source]

Raised when instantiating an abstract document

exception umongo.exceptions.AlreadyCreatedError[source]

Modifying id of an already created document

exception umongo.exceptions.AlreadyRegisteredDocumentError[source]

Document already registerd

exception umongo.exceptions.DeleteError[source]

Error while deleting document

exception umongo.exceptions.DocumentDefinitionError[source]

Error in document definition

exception umongo.exceptions.NoCompatibleInstanceError[source]

Can’t find instance compatible with database

exception umongo.exceptions.NoDBDefinedError[source]

No database defined

exception umongo.exceptions.NoneReferenceError[source]

Retrieving a None reference

exception umongo.exceptions.NotCreatedError[source]

Document does not exist in database

exception umongo.exceptions.NotRegisteredDocumentError[source]

Document not registered

exception umongo.exceptions.UMongoError[source]

Base umongo error

exception umongo.exceptions.UnknownFieldInDBError[source]

Data from database contains unknown field

exception umongo.exceptions.UpdateError[source]

Error while updating document