-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6th .py
77 lines (59 loc) · 2.18 KB
/
6th .py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import pymongo
from pymongo import MongoClient
# Connect to MongoDB cluster with MongoClient
client = MongoClient("mongodb://localhost:27017")
# Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
def callback(
session,
transfer_id=None,
account_id_receiver=None,
account_id_sender=None,
transfer_amount=None,
):
# Get reference to 'accounts' collection
accounts_collection = session.client.bank.accounts
# Get reference to 'transfers' collection
transfers_collection = session.client.bank.transfers
transfer = {
"transfer_id": transfer_id,
"to_account": account_id_receiver,
"from_account": account_id_sender,
"amount": {"$numberDecimal": transfer_amount},
}
# Transaction operations
# Important: You must pass the session to each operation
# Update sender account: subtract transfer amount from balance and add transfer ID
accounts_collection.update_one(
{"account_id": account_id_sender},
{
"$inc": {"balance": -transfer_amount},
"$push": {"transfers_complete": transfer_id},
},
session=session,
)
# Update receiver account: add transfer amount to balance and add transfer ID
accounts_collection.update_one(
{"account_id": account_id_receiver},
{
"$inc": {"balance": transfer_amount},
"$push": {"transfers_complete": transfer_id},
},
session=session,
)
# Add new transfer to 'transfers' collection
transfers_collection.insert_one(transfer, session=session)
print("Transaction successful")
return
def callback_wrapper(s):
callback(
s,
transfer_id="TR218721873",
account_id_receiver="MDB343652528",
account_id_sender="MDB574189300",
transfer_amount=100,
)
# 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 cancel on error)
session.with_transaction(callback_wrapper)
client.close()