Skip to content

Commit c65367b

Browse files
committed
PYTHON-1972 Add example usage for withTransaction API
1 parent 9cf0fbd commit c65367b

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

test/test_examples.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@
2727
from pymongo.write_concern import WriteConcern
2828

2929
from test import client_context, unittest, IntegrationTest
30-
from test.utils import rs_or_single_client
31-
30+
from test.utils import rs_client, rs_or_single_client
3231

3332
class TestSampleShellCommands(unittest.TestCase):
3433

@@ -1037,6 +1036,44 @@ def update_employee_info(session):
10371036
self.assertIsNotNone(employee)
10381037
self.assertEqual(employee['status'], 'Inactive')
10391038

1039+
MongoClient = lambda _: rs_client()
1040+
uriString = None
1041+
1042+
# Start Transactions withTxn API Example 1
1043+
1044+
# For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
1045+
# uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
1046+
# For a sharded cluster, connect to the mongos instances; e.g.
1047+
# uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
1048+
1049+
client = MongoClient(uriString)
1050+
wc_majority = WriteConcern("majority", wtimeout=1000)
1051+
1052+
# Prereq: Create collections. CRUD operations in transactions must be on existing collections.
1053+
client.get_database(
1054+
"mydb1", write_concern=wc_majority).foo.insert_one({'abc': 0})
1055+
client.get_database(
1056+
"mydb2", write_concern=wc_majority).bar.insert_one({'xyz': 0})
1057+
1058+
# Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
1059+
def callback(session):
1060+
collection_one = session.client.mydb1.foo
1061+
collection_two = session.client.mydb2.bar
1062+
1063+
# Important:: You must pass the session to the operations.
1064+
collection_one.insert_one({'abc': 1}, session=session)
1065+
collection_two.insert_one({'xyz': 999}, session=session)
1066+
1067+
# Step 2: Start a client session.
1068+
with client.start_session() as session:
1069+
# Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
1070+
session.with_transaction(
1071+
callback, read_concern=ReadConcern('local'),
1072+
write_concern=wc_majority,
1073+
read_preference=ReadPreference.PRIMARY)
1074+
1075+
# End Transactions withTxn API Example 1
1076+
10401077
@client_context.require_transactions
10411078
def test_transactions_beta(self):
10421079
# Transaction beta examples

0 commit comments

Comments
 (0)