21
21
22
22
.. code-block:: python
23
23
24
- with client.start_session(causal_consistency=True) as session:
24
+ async with client.start_session(causal_consistency=True) as session:
25
25
collection = client.db.collection
26
26
await collection.update_one({"_id": 1}, {"$set": {"x": 10}}, session=session)
27
27
secondary_c = collection.with_options(read_preference=ReadPreference.SECONDARY)
53
53
54
54
orders = client.db.orders
55
55
inventory = client.db.inventory
56
- with client.start_session() as session:
57
- async with session.start_transaction():
56
+ async with client.start_session() as session:
57
+ async with await session.start_transaction():
58
58
await orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
59
59
await inventory.update_one(
60
60
{"sku": "abc123", "qty": {"$gte": 100}},
61
61
{"$inc": {"qty": -100}},
62
62
session=session,
63
63
)
64
64
65
- Upon normal completion of ``async with session.start_transaction()`` block, the
65
+ Upon normal completion of ``async with await session.start_transaction()`` block, the
66
66
transaction automatically calls :meth:`AsyncClientSession.commit_transaction`.
67
67
If the block exits with an exception, the transaction automatically calls
68
68
:meth:`AsyncClientSession.abort_transaction`.
113
113
.. code-block:: python
114
114
115
115
# Each read using this session reads data from the same point in time.
116
- with client.start_session(snapshot=True) as session:
116
+ async with client.start_session(snapshot=True) as session:
117
117
order = await orders.find_one({"sku": "abc123"}, session=session)
118
118
inventory = await inventory.find_one({"sku": "abc123"}, session=session)
119
119
@@ -619,7 +619,7 @@ async def callback(session):
619
619
await inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}},
620
620
{"$inc": {"qty": -100}}, session=session)
621
621
622
- with client.start_session() as session:
622
+ async with client.start_session() as session:
623
623
await session.with_transaction(callback)
624
624
625
625
To pass arbitrary arguments to the ``callback``, wrap your callable
@@ -628,7 +628,7 @@ async def callback(session):
628
628
async def callback(session, custom_arg, custom_kwarg=None):
629
629
# Transaction operations...
630
630
631
- with client.start_session() as session:
631
+ async with client.start_session() as session:
632
632
await session.with_transaction(
633
633
lambda s: callback(s, "custom_arg", custom_kwarg=1))
634
634
0 commit comments