client_session -- Logical sessions for sequential operations#
Logical sessions for ordering sequential operations.
在 3.6 版本加入.
Causally Consistent Reads#
with client.start_session(causal_consistency=True) as session:
collection = client.db.collection
collection.update_one({"_id": 1}, {"$set": {"x": 10}}, session=session)
secondary_c = collection.with_options(read_preference=ReadPreference.SECONDARY)
# A secondary read waits for replication of the write.
secondary_c.find_one({"_id": 1}, session=session)
If causal_consistency is True (the default), read operations that use the session are causally after previous read and write operations. Using a causally consistent session, an application can read its own writes and is guaranteed monotonic reads, even when reading from replica set secondaries.
参见
The MongoDB documentation on causal-consistency.
Transactions#
在 3.7 版本加入.
MongoDB 4.0 adds support for transactions on replica set primaries. A
transaction is associated with a ClientSession. To start a transaction
on a session, use ClientSession.start_transaction() in a with-statement.
Then, execute an operation within the transaction by passing the session to the
operation:
orders = client.db.orders
inventory = client.db.inventory
with client.start_session() as session:
with session.start_transaction():
orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
inventory.update_one(
{"sku": "abc123", "qty": {"$gte": 100}},
{"$inc": {"qty": -100}},
session=session,
)
Upon normal completion of with session.start_transaction() block, the
transaction automatically calls ClientSession.commit_transaction().
If the block exits with an exception, the transaction automatically calls
ClientSession.abort_transaction().
In general, multi-document transactions only support read/write (CRUD) operations on existing collections. However, MongoDB 4.4 adds support for creating collections and indexes with some limitations, including an insert operation that would result in the creation of a new collection. For a complete description of all the supported and unsupported operations see the MongoDB server's documentation for transactions.
A session may only have a single active transaction at a time, multiple transactions on the same session can be executed in sequence.
Snapshot Reads#
在 3.12 版本加入.
MongoDB 5.0 adds support for snapshot reads. Snapshot reads are requested by
passing the snapshot option to
start_session().
If snapshot is True, all read operations that use this session read data
from the same snapshot timestamp. The server chooses the latest
majority-committed snapshot timestamp when executing the first read operation
using the session. Subsequent reads on this session read from the same
snapshot timestamp. Snapshot reads are also supported when reading from
replica set secondaries.
# Each read using this session reads data from the same point in time.
with client.start_session(snapshot=True) as session:
order = orders.find_one({"sku": "abc123"}, session=session)
inventory = inventory.find_one({"sku": "abc123"}, session=session)
Snapshot Reads Limitations#
Snapshot reads sessions are incompatible with causal_consistency=True.
Only the following read operations are supported in a snapshot reads session:
distinct()(on unsharded collections)
Classes#
- class pymongo.client_session.ClientSession(client: MongoClient, server_session: Any, options: SessionOptions, implicit: bool)#
A session for ordering sequential operations.
ClientSessioninstances are not thread-safe or fork-safe. They can only be used by one thread or process at a time. A singleClientSessioncannot be used to run multiple operations concurrently.Should not be initialized directly by application developers - to create a
ClientSession, callstart_session().- advance_cluster_time(cluster_time: Mapping[str, Any]) None#
Update the cluster time for this session.
- Parameters:
cluster_time: The
cluster_timefrom another ClientSession instance.
- advance_operation_time(operation_time: Timestamp) None#
Update the operation time for this session.
- Parameters:
operation_time: The
operation_timefrom another ClientSession instance.
- property client: MongoClient#
The
MongoClientthis session was created from.
- property cluster_time: ClusterTime | None#
The cluster time returned by the last operation executed in this session.
- end_session() None#
Finish this session. If a transaction has started, abort it.
It is an error to use the session after the session has ended.
- property in_transaction: bool#
True if this session has an active multi-statement transaction.
在 3.10 版本加入.
- property operation_time: Timestamp | None#
The operation time returned by the last operation executed in this session.
- property options: SessionOptions#
The
SessionOptionsthis session was created with.
- start_transaction(read_concern: ReadConcern | None = None, write_concern: WriteConcern | None = None, read_preference: _ServerMode | None = None, max_commit_time_ms: int | None = None) ContextManager#
Start a multi-statement transaction.
Takes the same arguments as
TransactionOptions.在 3.9 版本发生变更: Added the
max_commit_time_msoption.在 3.7 版本加入.
- with_transaction(callback: Callable[[ClientSession], _T], read_concern: ReadConcern | None = None, write_concern: WriteConcern | None = None, read_preference: _ServerMode | None = None, max_commit_time_ms: int | None = None) _T#
Execute a callback in a transaction.
This method starts a transaction on this session, executes
callbackonce, and then commits the transaction. For example:def callback(session): orders = session.client.db.orders inventory = session.client.db.inventory orders.insert_one({"sku": "abc123", "qty": 100}, session=session) inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}}, {"$inc": {"qty": -100}}, session=session) with client.start_session() as session: session.with_transaction(callback)
To pass arbitrary arguments to the
callback, wrap your callable with alambdalike this:def callback(session, custom_arg, custom_kwarg=None): # Transaction operations... with client.start_session() as session: session.with_transaction( lambda s: callback(s, "custom_arg", custom_kwarg=1))
In the event of an exception,
with_transactionmay retry the commit or the entire transaction, thereforecallbackmay be invoked multiple times by a single call towith_transaction. Developers should be mindful of this possibility when writing acallbackthat modifies application state or has any other side-effects. Note that even when thecallbackis invoked multiple times,with_transactionensures that the transaction will be committed at-most-once on the server.The
callbackshould not attempt to start new transactions, but should simply run operations meant to be contained within a transaction. Thecallbackshould also not commit the transaction; this is handled automatically bywith_transaction. If thecallbackdoes commit or abort the transaction without error, however,with_transactionwill return without taking further action.ClientSessioninstances are not thread-safe or fork-safe. Consequently, thecallbackmust not attempt to execute multiple operations concurrently.When
callbackraises an exception,with_transactionautomatically aborts the current transaction. Whencallbackorcommit_transaction()raises an exception that includes the"TransientTransactionError"error label,with_transactionstarts a new transaction and re-executes thecallback.When
commit_transaction()raises an exception with the"UnknownTransactionCommitResult"error label,with_transactionretries the commit until the result of the transaction is known.This method will cease retrying after 120 seconds has elapsed. This timeout is not configurable and any exception raised by the
callbackor byClientSession.commit_transaction()after the timeout is reached will be re-raised. Applications that desire a different timeout duration should not use this method.- Parameters:
callback: The callable
callbackto run inside a transaction. The callable must accept a single argument, this session. Note, under certain error conditions the callback may be run multiple times.read_concern (optional): The
ReadConcernto use for this transaction.write_concern (optional): The
WriteConcernto use for this transaction.read_preference (optional): The read preference to use for this transaction. If
None(the default) theread_preferenceof thisDatabaseis used. Seeread_preferencesfor options.
- Returns:
The return value of the
callback.
在 3.9 版本加入.
- class pymongo.client_session.SessionOptions(causal_consistency: bool | None = None, default_transaction_options: TransactionOptions | None = None, snapshot: bool | None = False)#
Options for a new
ClientSession.- Parameters:
causal_consistency (optional): If True, read operations are causally ordered within the session. Defaults to True when the
snapshotoption isFalse.default_transaction_options (optional): The default TransactionOptions to use for transactions started on this session.
snapshot (optional): If True, then all reads performed using this session will read from the same snapshot. This option is incompatible with
causal_consistency=True. Defaults toFalse.
在 3.12 版本发生变更: Added the
snapshotparameter.- property default_transaction_options: TransactionOptions | None#
The default TransactionOptions to use for transactions started on this session.
在 3.7 版本加入.
- class pymongo.client_session.TransactionOptions(read_concern: ReadConcern | None = None, write_concern: WriteConcern | None = None, read_preference: _ServerMode | None = None, max_commit_time_ms: int | None = None)#
Options for
ClientSession.start_transaction().- Parameters:
read_concern (optional): The
ReadConcernto use for this transaction. IfNone(the default) theread_preferenceof theMongoClientis used.write_concern (optional): The
WriteConcernto use for this transaction. IfNone(the default) theread_preferenceof theMongoClientis used.read_preference (optional): The read preference to use. If
None(the default) theread_preferenceof thisMongoClientis used. Seeread_preferencesfor options. Transactions which read must usePRIMARY.max_commit_time_ms (optional): The maximum amount of time to allow a single commitTransaction command to run. This option is an alias for maxTimeMS option on the commitTransaction command. If
None(the default) maxTimeMS is not used.
在 3.9 版本发生变更: Added the
max_commit_time_msoption.在 3.7 版本加入.
- property max_commit_time_ms: int | None#
The maxTimeMS to use when running a commitTransaction command.
在 3.9 版本加入.
- property read_concern: ReadConcern | None#
This transaction's
ReadConcern.
- property read_preference: _ServerMode | None#
This transaction's
ReadPreference.
- property write_concern: WriteConcern | None#
This transaction's
WriteConcern.