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 its name or its 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

alias of 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 inherits 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.

property collection

Return the collection used by this document class

property 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_modified()[source]

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

property 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

alias of 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

alias of 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: types.ErrorMessages = {'unique': 'Field value must be unique.', 'unique_compound': 'Values of fields {fields} must be unique together.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

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.

property error

The type of the None singleton.

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

alias of BooleanField

class umongo.fields.BooleanField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.ConstantField(*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.DateTimeField(*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.DictField(*args, **kwargs)[source]
as_marshmallow_field()[source]

Return a pure-marshmallow version of this field

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

Return a pure-marshmallow version of this field

property 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

property nested
class umongo.fields.FloatField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]
class umongo.fields.GenericReferenceField(*args, reference_cls=<class 'umongo.data_objects.Reference'>, **kwargs)[source]
umongo.fields.IntField

alias of IntegerField

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

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

umongo.fields.StrField

alias of StringField

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

alias of UrlField

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

Data objects

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 the key is not found, return the default if given; otherwise, raise a KeyError.

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

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict 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 mapping/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E.keys(): 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.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]

Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.

class umongo.data_objects.Reference(document_cls, pk)[source]
error_messages = {'not_found': 'Reference not found for document {document}.'}
property exists

Check if the reference document exists in the database.

fetch(no_data=False, force_reload=False, projection=None)[source]

Retrieve from the database the referenced document

Parameters:
  • no_data – if True, the caller is only interested in whether 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.

  • projection – if supplied, this is a dictionary or list describing a projection which limits the data returned from database.

Marshmallow integration

Pure marshmallow fields used in umongo

class umongo.marshmallow_bonus.GenericReference(*, load_default: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, pre_load: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, post_load: ~typing.Callable[[~marshmallow.types.T], ~marshmallow.types.T] | ~typing.Iterable[~typing.Callable[[~marshmallow.types.T], ~marshmallow.types.T]] | None = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str | list | dict] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None)[source]

Marshmallow field for umongo.fields.GenericReferenceField

class umongo.marshmallow_bonus.ObjectId(*, load_default: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, pre_load: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, post_load: ~typing.Callable[[~marshmallow.types.T], ~marshmallow.types.T] | ~typing.Iterable[~typing.Callable[[~marshmallow.types.T], ~marshmallow.types.T]] | None = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str | list | dict] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None)[source]

Marshmallow field for bson.objectid.ObjectId

class umongo.marshmallow_bonus.Reference(*, load_default: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, pre_load: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, post_load: ~typing.Callable[[~marshmallow.types.T], ~marshmallow.types.T] | ~typing.Iterable[~typing.Callable[[~marshmallow.types.T], ~marshmallow.types.T]] | None = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str | list | dict] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None)[source]

Marshmallow field for umongo.fields.ReferenceField

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