ming.odm module

class ming.odm.declarative.MappedClass

Declares a Ming Mapped Document.

Mapped Documents provide a declarative interface to schema, relations and properties declaration for your Models stored as MongoDB Documents.

MappedClasses required that a __mongometa__ subclass is available inside which provides the details regarding the name of the collection storing the documents and the session used to store the documents:

class WikiPage(MappedClass):
    class __mongometa__:
        session = session
        name = 'wiki_page'

    _id = FieldProperty(schema.ObjectId)
    title = FieldProperty(schema.String(required=True))
    text = FieldProperty(schema.String(if_missing=''))
ming.odm.base.session(v) → ODMSession

Returns the ORMSession instance managing either a class or an object

ming.odm.base.state(obj) → ming.odm.base.ObjectState

Gets the UnitOfWork state of a mapped object

exception ming.odm.property.AmbiguousJoin
class ming.odm.property.FieldProperty(field_type, *args, **kwargs)

Declares property for a value stored in a MongoDB Document.

The provided arguments are just forwarded to Field class which is actually in charge of managing the value and its validation.

For details on available options in FieldProperty just rely on Field documentation.

include_in_repr

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

class ming.odm.property.FieldPropertyWithMissingNone(field_type, *args, **kwargs)

A class like FieldProperty with one exception. If you use if_missing=S.Missing with FieldPropertyWithMissingNone when a value in Mongo is not present, instead of Ming throwing an AttributeError, Ming will return a value of None for that attribute.

class ming.odm.property.ForeignIdProperty(related, uselist=False, allow_none=False, *args, **kwargs)

Declares a field to store one or more ObjectIds of a related objects.

The related argument must be the related entity class or the name of the related entity class (to avoid circular dependencies). The field itself will actually store and retrieve bson.ObjectId instances.

uselist argument can be used to tell Ming whenever the object can relate to more than one remote object (many-to-many) and so the ids are stored in a MongoDB Array.

Usually a ForeignIdProperty with value None means that the object is not related to any other entity, in case you have entities that might have None as their ids you can use allow_none option to tell Ming that None is a valid foreign id.

exception ming.odm.property.NoJoin
exception ming.odm.property.ORMError
class ming.odm.property.RelationProperty(related, via=None, fetch=True)

Provides a way to access OneToMany, ManyToOne and ManyToMany relations.

The RelationProperty relies on ForeignIdProperty to actually understand how the relation is composed and how to retrieve the related data.

Assigning a new value to the relation will properly update the related objects.

class ming.odm.odmsession.ODMCursor(session, cls, ming_cursor, refresh=False, decorate=None, fields=None)

Represents the results of query.

The cursors can be iterated over to retrieve the results one by one.

all()

Retrieve all the results of the query

count()

Get the number of objects retrieved by the query

first()

Gets the first result of the query

limit(limit)

Limit the number of entries retrieved by the query

one()

Gets one result and exaclty one.

Raises ValueError exception if less or more than one result is returned by the query.

rewind()

Rewind this cursor to its unevaluated state. Reset this cursor if it has been partially or completely evaluated. Any options that are present on the cursor will remain in effect. Future iterating performed on this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor.

skip(skip)

Skip the first skip entries retrieved by the query

sort(*args, **kwargs)

Sort results of the query.

See pymongo.cursor.Cursor.sort() for details on the available arguments.

class ming.odm.odmsession.ODMSession(doc_session: ming.session.Session = None, bind: ming.datastore.DataStore = None, extensions=None, autoflush=False)

Current Ming Session.

Keeps track of active objects in the IdentityMap and UnitOfWork and of the current connection to the database. All the operation on MongoDB should happen through the ODMSession to avoid inconsistent state between objects updated through the session and outside the session.

aggregate(cls, *args, **kwargs)

Runs an aggregation pipeline on the given collection.

Arguments are the same as pymongo.collection.Collection.aggregate().

classmethod by_name(name)

Retrieve or create a new Session with the given name.

This is useful to keep around multiple sessions and identify them by name. The session registry is global so they are available everywhere as far as the ming module is the same.

clear()

Expunge all the objects from the session.

close()

Clear the session.

db

Access the low-level pymongo database

distinct(cls, *args, **kwargs)

Get a list of distinct values for a key among all documents in this collection.

Arguments are the same as pymongo.collection.Collection.distinct().

drop_indexes(cls)

Drop all indexes declared in cls

ensure_indexes(cls)

Ensures all indexes declared in cls

expunge(obj)

Remove an object from the Session (and its UnitOfWork and IdentityMap)

find(cls, *args, **kwargs)

Retrieves cls by performing a mongodb query.

This is the same as calling cls.query.find() and always performs a query on the database. According to the refresh argument the objects are also updated in the UnitOfWork or not. Otherwise the UnitOfWork keeps the old object state which is the default.

If the session has autoflush option, the session if flushed before performing the query.

Arguments are the same as pymongo.collection.Collection.find() plus the following additional arguments:

  • allow_extra Whenever to raise an exception in case of extra fields not specified in the model definition.
  • strip_extra Whenever extra fields should be stripped if present.
  • validate Disable validation or not.

It returns an ODMCursor with the results.

find_and_modify(cls, *args, **kwargs)

Finds and updates cls.

Arguments are the same as pymongo.collection.Collection.find_and_modify().

If the session has autoflush option, the session if flushed before performing the query.

It returns an ODMCursor with the results.

flush(*args, **kwargs)

Flush obj or all the objects in the UnitOfWork.

When obj is provided, only obj is flushed to the database, otherwise all the objects in the UnitOfWork are persisted on the databases according to their current state.

get(cls, idvalue)

Retrieves cls by its _id value passed as idvalue.

If the object is already available in the IdentityMap this acts as a simple cache a returns the current object without querying the database. Otherwise a find query is issued and the object retrieved.

This the same as calling cls.query.get(_id=idvalue).

group(cls, *args, **kwargs)

Runs a grouping on the model collection.

Arguments are the same as pymongo.collection.Collection.group().

inline_map_reduce(cls, *args, **kwargs)

Runs a MapReduce job and keeps results in-memory.

Arguments are the same as pymongo.collection.Collection.inline_map_reduce().

map_reduce(cls, *args, **kwargs)

Runs a MapReduce job and stores results in a collection.

Arguments are the same as pymongo.collection.Collection.map_reduce().

refresh(obj)

Refreshes the object in the session by querying it back and updating its state

remove(*args, **kwargs)

Delete one or more cls entries from the collection.

This performs the delete operation outside of the UnitOfWork, so the objects already in the UnitOfWork and IdentityMap are unaffected and might be recreated when the session is flushed.

Arguments are the same as pymongo.collection.Collection.remove().

save(obj)

Add an object to the Session (and its UnitOfWork and IdentityMap).

Usually objects are automatically added to the session when created. This is done by _InitDecorator.saving_init() which is the __init__ method of all the :class`.MappedClass` subclasses instrumented by Mapper.

So calling this method is usually not required unless the object was expunged.

update(cls, spec, fields, **kwargs)

Updates one or more cls entries from the collection.

This performs the update operation outside of the UnitOfWork, so the objects already in the UnitOfWork and IdentityMap are unaffected and might be restored to previous state when the session is flushed.

Arguments are the same as pymongo.collection.Collection.update().

update_if_not_modified(obj, fields, upsert=False)

Updates one entry unless it was modified since first queried.

Arguments are the same as pymongo.collection.Collection.update().

Returns whenever the update was performed or not.

class ming.odm.odmsession.SessionExtension(session)

Base class that should be inherited to handle Session events.

after_cursor_next(cursor)

Cursor has advanced to next result

after_delete(obj, st)

After an object gets deleted in this session

after_flush(obj=None)

After the session is flushed for obj

If obj is None it means all the objects in the UnitOfWork which can be retrieved by iterating over ODMSession.uow

after_insert(obj, st)

After an object gets inserted in this session

after_remove(cls, *args, **kwargs)

After a remove query is performed session

after_update(obj, st)

After an object gets updated in this session

before_cursor_next(cursor)

Cursor is going to advance to next result

before_delete(obj, st)

Before an object gets deleted in this session

before_flush(obj=None)

Before the session is flushed for obj

If obj is None it means all the objects in the UnitOfWork which can be retrieved by iterating over ODMSession.uow

before_insert(obj, st)

Before an object gets inserted in this session

before_remove(cls, *args, **kwargs)

Before a remove query is performed session

before_update(obj, st)

Before an object gets updated in this session

cursor_created(cursor, action, *args, **kw)

New cursor with the results of a query got created

class ming.odm.odmsession.ThreadLocalODMSession(*args, **kwargs)

ThreadLocalODMSession is a thread-safe proxy to ODMSession.

This routes properties and methods to the session in charge of the current thread. For a reference of available methods and properties refer to the ODMSession.

classmethod by_name(name)

Retrieve or create a new ThreadLocalODMSession with the given name.

This is useful to keep around multiple sessions and identify them by name. The session registry is global so they are available everywhere as far as the ming module is the same.

classmethod close_all()

Closes all the ODMSessions registered in current thread, which clears their objects tracked in memory.

Does not close connections.

classmethod flush_all()

Flush all the ODMSessions registered in current thread

Usually is not necessary as only one session is registered per-thread.

class ming.odm.mapper.Mapper(mapped_class, collection, session, **kwargs)

Keeps track of MappedClass subclasses.

The Mapper is in charge of linking together the Ming Schema Validation layer, the Session and a MappedClass. It also compiles the Schema Validation for Mapped Classes if they don’t already have one.

Mapper also instruments mapped classes by adding the additional .query property and behaviours.

You usually won’t be using the Mapper directly apart from compile_all() and ensure_all_indexes() methods.

classmethod compile_all()

Compiles Schema Validation details for all MappedClass subclasses

classmethod ensure_all_indexes()

Ensures indexes for each registered MappedClass subclass are created

class ming.odm.mapper.MapperExtension(mapper)

Base class that should be inherited to handle Mapper events.

after_delete(instance, state, sess)

Receive an object instance and its current state after that instance is deleted.

after_insert(instance, state, sess)

Receive an object instance and its current state after that instance is inserted into its collection.

after_remove(sess, *args, **kwargs)

After a remove query is performed for this class

after_update(instance, state, sess)

Receive an object instance and its current state after that instance is updated.

before_delete(instance, state, sess)

Receive an object instance and its current state before that instance is deleted.

before_insert(instance, state, sess)

Receive an object instance and its current state before that instance is inserted into its collection.

before_remove(sess, *args, **kwargs)

Before a remove query is performed for this class

before_update(instance, state, sess)

Receive an object instance and its current state before that instance is updated.

ming.odm.mapper.mapper(cls, collection=None, session=None, **kwargs)

Gets or creates the mapper for the given cls MappedClass

class ming.odm.middleware.MingMiddleware(app, context_func=None, flush_on_errors=())

WSGI Middleware that automatically flushes and closes ODM Sessions.

At the end of each WSGI request for app the middleware will automatically flush the session unless there was an Exception, then it will close the session to clear it.

flush_on_errors can be a list of exception types for which the session should be flushed anyway. This usually includes webob.exc.HTTPRedirection subclasses if WebOb is available.