PYTHON-1972 Add example usage for withTransaction API
This commit is contained in:
parent
9cf0fbd785
commit
c65367b8f0
@ -27,8 +27,7 @@ from pymongo.read_preferences import ReadPreference
|
||||
from pymongo.write_concern import WriteConcern
|
||||
|
||||
from test import client_context, unittest, IntegrationTest
|
||||
from test.utils import rs_or_single_client
|
||||
|
||||
from test.utils import rs_client, rs_or_single_client
|
||||
|
||||
class TestSampleShellCommands(unittest.TestCase):
|
||||
|
||||
@ -1037,6 +1036,44 @@ class TestTransactionExamples(IntegrationTest):
|
||||
self.assertIsNotNone(employee)
|
||||
self.assertEqual(employee['status'], 'Inactive')
|
||||
|
||||
MongoClient = lambda _: rs_client()
|
||||
uriString = None
|
||||
|
||||
# Start Transactions withTxn API Example 1
|
||||
|
||||
# For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
|
||||
# uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
|
||||
# For a sharded cluster, connect to the mongos instances; e.g.
|
||||
# uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
|
||||
|
||||
client = MongoClient(uriString)
|
||||
wc_majority = WriteConcern("majority", wtimeout=1000)
|
||||
|
||||
# Prereq: Create collections. CRUD operations in transactions must be on existing collections.
|
||||
client.get_database(
|
||||
"mydb1", write_concern=wc_majority).foo.insert_one({'abc': 0})
|
||||
client.get_database(
|
||||
"mydb2", write_concern=wc_majority).bar.insert_one({'xyz': 0})
|
||||
|
||||
# Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
|
||||
def callback(session):
|
||||
collection_one = session.client.mydb1.foo
|
||||
collection_two = session.client.mydb2.bar
|
||||
|
||||
# Important:: You must pass the session to the operations.
|
||||
collection_one.insert_one({'abc': 1}, session=session)
|
||||
collection_two.insert_one({'xyz': 999}, session=session)
|
||||
|
||||
# Step 2: Start a client session.
|
||||
with client.start_session() as session:
|
||||
# Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
|
||||
session.with_transaction(
|
||||
callback, read_concern=ReadConcern('local'),
|
||||
write_concern=wc_majority,
|
||||
read_preference=ReadPreference.PRIMARY)
|
||||
|
||||
# End Transactions withTxn API Example 1
|
||||
|
||||
@client_context.require_transactions
|
||||
def test_transactions_beta(self):
|
||||
# Transaction beta examples
|
||||
|
||||
Loading…
Reference in New Issue
Block a user