txmongo package

Submodules

txmongo.collection module

class txmongo.collection.Collection(database, name, write_concern=None, codec_options=None)[source]

Bases: object

Creates new Collection object

Parameters:
  • database – the Database instance to get collection from
  • name – the name of the collection to get
  • write_concern – An instance of WriteConcern. If None, database.write_concern is used.
  • codec_options – An instance of CodecOptions. If None, database.codec_options is used.
aggregate(pipeline, full_response=False, **kwargs)[source]
bulk_write(requests, ordered=True)[source]
codec_options

Read only access to the CodecOptions of this instance.

Use coll.with_options(codec_options=CodecOptions(...)) to change codec options.

count(spec=None, **kwargs)[source]

Get the number of documents in this collection.

Parameters:
  • spec – argument is a query document that selects which documents to count in the collection.
  • hint(keyword only) hint instance specifying index to use.
Returns:

a Deferred that called back with a number of documents matching the criteria.

create_index(sort_fields, **kwargs)[source]
database

The Database that this Collection is a part of.

delete_many(filter, **kwargs)[source]
delete_one(filter, **kwargs)[source]
distinct(key, spec=None, **kwargs)[source]
drop(**kwargs)[source]
drop_index(index_identifier, **kwargs)[source]
drop_indexes(**kwargs)[source]
ensure_index(sort_fields, **kwargs)[source]
filemd5(spec, **kwargs)[source]
find(spec=None, skip=0, limit=0, fields=None, filter=None, cursor=False, **kwargs)[source]

Find documents in a collection.

The spec argument is a MongoDB query document. To return all documents in a collection, omit this parameter or pass an empty document ({}). You can pass {"key": "value"} to select documents having key field equal to "value" or use any of MongoDB’s query selectors.

Ordering, indexing hints and other query parameters can be set with filter argument. See txmongo.filter for details.

Parameters:
  • skip – the number of documents to omit from the start of the result set.
  • limit – the maximum number of documents to return. All documents are returned when limit is zero.
  • fields – a list of field names that should be returned for each document in the result set or a dict specifying field names to include or exclude. If fields is a list _id fields will always be returned. Use a dict form to exclude fields: fields={"_id": False}.
  • as_class(keyword only) if not None, returned documents will be converted to type specified. For example, you can use as_class=collections.OrderedDict or as_class=bson.SON when field ordering in documents is important.
Returns:

an instance of Deferred that called back with one of:

  • if cursor is False (the default) — all documents found

  • if cursor is True — tuple of (docs, dfr), where docs is a partial result, returned by MongoDB in a first batch and dfr is a Deferred that fires with next (docs, dfr). Last result will be ([], None). Using this mode you can iterate over the result set with code like that:

    @defer.inlineCallbacks
    def query():
        docs, dfr = yield coll.find(query, cursor=True)
        while docs:
            for doc in docs:
                do_something(doc)
            docs, dfr = yield dfr
    

find_and_modify(query=None, update=None, upsert=False, **kwargs)[source]
find_one(spec=None, fields=None, **kwargs)[source]

Get a single document from the collection.

All arguments to find() are also valid for find_one(), although limit will be ignored.

Returns:a Deferred that called back with single document or None if no matching documents is found.
find_one_and_delete(filter, projection=None, sort=None, **kwargs)[source]
find_one_and_replace(filter, replacement, projection=None, sort=None, upsert=False, return_document=False, **kwargs)[source]
find_one_and_update(filter, update, projection=None, sort=None, upsert=False, return_document=False, **kwargs)[source]
find_with_cursor(spec=None, skip=0, limit=0, fields=None, filter=None, **kwargs)[source]

Find documents in a collection and return them in one batch at a time

This methid is equivalent of find() with cursor=True. See find() for description of parameters and return value.

full_name

Full name of this Collection, i.e. db_name.collection_name

group(keys, initial, reduce, condition=None, finalize=None, **kwargs)[source]
index_information(**kwargs)[source]
insert(docs, safe=None, flags=0, **kwargs)[source]

Insert a document(s) into this collection.

Please consider using new-style insert_one() or insert_many() methods instead.

If document doesn’t have "_id" field, insert() will generate new ObjectId and set it to "_id" field of the document.

Parameters:
  • docs – Document or a list of documents to insert into a collection.
  • safeTrue or False forces usage of respectively acknowledged or unacknowledged Write Concern. If None, write_concern is used.
  • flags – If zero (default), inserting will stop after the first error encountered. When flags set to txmongo.protocol.INSERT_CONTINUE_ON_ERROR, MongoDB will try to insert all documents passed even if inserting some of them will fail (for example, because of duplicate _id). Not that insert() won’t raise any errors when this flag is used.
Returns:

Deferred that fires with single _id field or a list of _id fields of inserted documents.

insert_many(documents, ordered=True, **kwargs)[source]

Insert an iterable of documents into collection

Parameters:
  • documents – An iterable of documents to insert (list, tuple, ...)
  • ordered – If True (the default) documents will be inserted on the server serially, in the order provided. If an error occurs, all remaining inserts are aborted. If False, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted.
Returns:

Deferred that called back with pymongo.results.InsertManyResult

insert_one(document, **kwargs)[source]

Insert a single document into collection

Parameters:document – Document to insert
Returns:Deferred that called back with pymongo.results.InsertOneResult
map_reduce(map, reduce, full_response=False, **kwargs)[source]
name

Name of this Collection (without database name).

options(**kwargs)[source]

Get the options set on this collection.

Returns:Deferred that called back with dictionary of options and their values.
remove(spec, safe=None, single=False, flags=0, **kwargs)[source]
rename(new_name, **kwargs)[source]
replace_one(filter, replacement, upsert=False, **kwargs)[source]

Replace a single document matching the filter.

Raises:
  • ValueError – if update document is empty
  • ValueError – if update document has fields that starts with $ sign. This method only allows replacing document completely. Use update_one() for modifying existing document.
Parameters:
  • filter – A query that matches the document to replace.
  • replacement – The new document to replace with.
  • upsert – If True, perform an insert if no documents match the filter.
Returns:

deferred instance of pymongo.results.UpdateResult.

save(doc, safe=None, **kwargs)[source]
update(spec, document, upsert=False, multi=False, safe=None, flags=0, **kwargs)[source]

Update document(s) in this collection

Please consider using new-style update_one(), update_many() and replace_one() methods instead.

Raises:

TypeError – if spec or document are not instances of dict or upsert is not an instance of bool.

Parameters:
  • spec – query document that selects documents to be updated
  • document – update document to be used for updating or upserting. See MongoDB Update docs for the format of this document and allowed operators.
  • upsert – perform an upsert if True
  • multi – update all documents that match spec, rather than just the first matching document. The default value is False.
  • safeTrue or False forces usage of respectively acknowledged or unacknowledged Write Concern. If None, write_concern is used.
Returns:

Deferred that is called back when request is sent to MongoDB or confirmed by MongoDB (depending on selected Write Concern).

update_many(filter, update, upsert=False, **kwargs)[source]

Update one or more documents that match the filter.

Raises:
  • ValueError – if update document is empty.
  • ValueError – if update document has fields that don’t start with $ sign. This method only allows modification of document (with $set, $inc, etc.), not replacing it. For replacing use replace_one() instead.
Parameters:
  • filter – A query that matches the documents to update.
  • update

    update document to be used for updating or upserting. See MongoDB Update docs for allowed operators.

  • upsert – If True, perform an insert if no documents match the filter.
Returns:

deferred instance of pymongo.results.UpdateResult.

update_one(filter, update, upsert=False, **kwargs)[source]

Update a single document matching the filter.

Raises:
  • ValueError – if update document is empty.
  • ValueError – if update document has any fields that don’t start with $ sign. This method only allows modification of document (with $set, $inc, etc.), not replacing it. For replacing use replace_one() instead.
Parameters:
  • filter – A query that matches the document to update.
  • update

    update document to be used for updating or upserting. See MongoDB Update docs for allowed operators.

  • upsert – If True, perform an insert if no documents match the filter.
Returns:

deferred instance of pymongo.results.UpdateResult.

with_options(**kwargs)[source]

Get a clone of collection changing the specified settings.

Parameters:
  • write_concern(keyword only) new WriteConcern to use.
  • codec_options(keyword only) new CodecOptions to use.
write_concern

Read only access to the WriteConcern of this instance.

Use coll.with_options(write_concern=WriteConcern(...)) to change the Write Concern.

txmongo.connection module

class txmongo.connection.ConnectionPool(uri='mongodb://127.0.0.1:27017', pool_size=1, ssl_context_factory=None, watchdog_interval=30, watchdog_timeout=120, **kwargs)[source]

Bases: object

authenticate(database, username, password, mechanism='DEFAULT')[source]
codec_options
disconnect()[source]
get_default_database()[source]
getprotocol()[source]
getprotocols()[source]
uri
write_concern
class txmongo.connection.MongoConnection(host='127.0.0.1', port=27017, pool_size=1, **kwargs)[source]

Bases: txmongo.connection.ConnectionPool

txmongo.connection.MongoConnectionPool

alias of MongoConnection

txmongo.connection.lazyMongoConnection

alias of MongoConnection

txmongo.connection.lazyMongoConnectionPool

alias of MongoConnection

txmongo.database module

class txmongo.database.Database(factory, database_name, write_concern=None, codec_options=None)[source]

Bases: object

authenticate(name, password, mechanism='DEFAULT')[source]

Send an authentication command for this database. mostly stolen from pymongo

codec_options
collection_names(**kwargs)[source]
command(command, value=1, check=True, allowable_errors=None, **kwargs)[source]
connection
create_collection(name, options=None, **kwargs)[source]
drop_collection(name_or_collection, **kwargs)[source]
name
write_concern

txmongo.filter module

txmongo.filter.ASCENDING(keys)[source]

Ascending sort order

txmongo.filter.DESCENDING(keys)[source]

Descending sort order

txmongo.filter.GEO2D(keys)[source]

Two-dimensional geospatial index http://www.mongodb.org/display/DOCS/Geospatial+Indexing

txmongo.filter.GEO2DSPHERE(keys)[source]

Two-dimensional geospatial index http://www.mongodb.org/display/DOCS/Geospatial+Indexing

txmongo.filter.GEOHAYSTACK(keys)[source]

Bucket-based geospatial index http://www.mongodb.org/display/DOCS/Geospatial+Haystack+Indexing

class txmongo.filter.comment(comment)[source]

Bases: txmongo.filter._QueryFilter

class txmongo.filter.explain[source]

Bases: txmongo.filter._QueryFilter

Returns an explain plan for the query.

class txmongo.filter.hint(index_list_or_name)[source]

Bases: txmongo.filter._QueryFilter

Adds a hint, telling Mongo the proper index to use for the query.

class txmongo.filter.snapshot[source]

Bases: txmongo.filter._QueryFilter

class txmongo.filter.sort(key_list)[source]

Bases: txmongo.filter._QueryFilter

Sorts the results of a query.

txmongo.gridfs module

txmongo.protocol module

Low level connection to Mongo.

This module contains the wire protocol implementation for txmongo. The various constants from the protocol are available as constants.

This implementation requires pymongo so that as much of the implementation can be shared. This includes BSON encoding and decoding as well as Exception types, when applicable.

class txmongo.protocol.Delete[source]

Bases: txmongo.protocol.Delete

class txmongo.protocol.Getmore[source]

Bases: txmongo.protocol.Getmore

class txmongo.protocol.Insert[source]

Bases: txmongo.protocol.Insert

class txmongo.protocol.KillCursors[source]

Bases: txmongo.protocol.KillCursors

exception txmongo.protocol.MongoAuthenticationError[source]

Bases: Exception

class txmongo.protocol.MongoClientProtocol[source]

Bases: twisted.internet.protocol.Protocol

get_request_id()[source]
send(request)[source]
send_DELETE(request)[source]
send_GETMORE(request)[source]
send_INSERT(request)[source]
send_KILL_CURSORS(request)[source]
send_MSG(request)[source]
send_QUERY(request)[source]
send_REPLY(request)[source]
send_UPDATE(request)[source]
class txmongo.protocol.MongoDecoder[source]

Bases: object

dataBuffer = None
static decode(message_data)[source]
feed(data)[source]
next()
class txmongo.protocol.MongoProtocol[source]

Bases: txmongo.protocol.MongoServerProtocol, txmongo.protocol.MongoClientProtocol

authenticate(database_name, username, password, mechanism)[source]
authenticate_mongo_cr(database_name, username, password)[source]
authenticate_scram_sha1(database_name, username, password)[source]
connectionLost(reason=<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>)[source]
connectionMade()[source]
connectionReady()[source]
fail(reason)[source]
get_last_error(db, **options)[source]
handle_REPLY(request)[source]
inflight()[source]
max_wire_version = None
min_wire_version = None
send_GETMORE(request)[source]
send_QUERY(request)[source]
set_wire_versions(min_wire_version, max_wire_version)[source]
class txmongo.protocol.MongoServerProtocol[source]

Bases: twisted.internet.protocol.Protocol

dataReceived(data)[source]
handle(request)[source]
handle_DELETE(request)[source]
handle_GETMORE(request)[source]
handle_INSERT(request)[source]
handle_KILL_CURSORS(request)[source]
handle_MSG(request)[source]
handle_QUERY(request)[source]
handle_REPLY(request)[source]
handle_UPDATE(request)[source]
class txmongo.protocol.Msg(len, request_id, response_to, opcode, message)

Bases: tuple

len

Alias for field number 0

message

Alias for field number 4

opcode

Alias for field number 3

request_id

Alias for field number 1

response_to

Alias for field number 2

class txmongo.protocol.Query[source]

Bases: txmongo.protocol.Query

class txmongo.protocol.Reply[source]

Bases: txmongo.protocol.Reply

class txmongo.protocol.Update[source]

Bases: txmongo.protocol.Update

Module contents