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.Documentandumongo.EmbeddedDocument.- register(template)[source]¶
Generate an
umongo.template.Implementationfrom the givenumongo.template.Templatefor this instance.- Parameters:
template –
umongo.template.Templateto implement- Returns:
The
umongo.template.Implementationgenerated
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.DocumentImplementationregistered 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.EmbeddedDocumentImplementationregistered into this instance from it name or it template class (i.e.umongo.EmbeddedDocument).
- class umongo.frameworks.pymongo.PyMongoInstance(db=None)[source]¶
umongo.instance.Instanceimplementation 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.BaseInstanceto obtain it correspondingumongo.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
_clsfield, 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
- from_mongo(data)[source]¶
Update the document with the MongoDB data
- Parameters:
data – data as retrieved from MongoDB
- property pk¶
Return the document’s primary key (i.e.
_idin mongo notation) or None if not available yetWarning
Use
is_createdfield instead to test if the document has already been commited to database given_idfield 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.
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.BaseInstanceto obtain it correspondingumongo.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.
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.BaseInstanceto obtain it correspondingumongo.mixin.MixinDocumentImplementation.
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
- 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_'¶
- 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.
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.EmailField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]¶
- class umongo.fields.EmbeddedField(embedded_document, *args, **kwargs)[source]¶
-
- property embedded_document_cls¶
Return the instance’s
umongo.embedded_document.EmbeddedDocumentImplementationimplementing the embedded_document attribute.
- 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.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.DocumentImplementationimplementing the document attribute.
- umongo.fields.StrField¶
alias of
StringField
- class umongo.fields.StringField(*args, io_validate=None, unique=False, instance=None, **kwargs)[source]¶
Data objects¶
- class umongo.data_objects.Dict(key_field, value_field, *args, **kwargs)[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.
- 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]¶
-
- inner_field¶
- 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.
- 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.NoCompatibleInstanceError[source]¶
Can’t find instance compatible with database