Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pymongo import MongoClient, ReadPreference, WriteConcern
- from pymongo.read_concern import ReadConcern
- from time import sleep
- from threading import Thread
- from dotenv import dotenv_values
- config = dotenv_values(".env")
- def first_transaction():
- client = MongoClient(config["MONGO_URI"])
- db = client["test"]
- collection = db["transaction_test"]
- sleep(5)
- while True:
- try:
- with client.start_session() as session:
- session.start_transaction(
- read_concern=ReadConcern(level="snapshot"),
- write_concern=WriteConcern(w="majority"),
- read_preference=ReadPreference.PRIMARY
- )
- doc = collection.find_one({"id": 1}, session=session)
- print(f"Thread 1 read value: {doc.get('value') if doc else None}")
- sleep(10)
- print("Thread 1 attempting write")
- result = collection.update_one({"id": 1}, {"$inc": {"value": -1}}, session=session)
- print(f"Thread 1 write result: {result.modified_count} modified")
- session.commit_transaction()
- print("Thread 1 committed transaction")
- sleep(5)
- except Exception as e:
- print(f"Thread 1 unexpected error: {e}")
- def second_transaction():
- client = MongoClient(config["MONGO_URI"])
- db = client["test"]
- collection = db["transaction_test"]
- while True:
- try:
- print("Thread 2 attempting write")
- result = collection.update_one({"id": 1}, {"$inc": {"value": 2}})
- print(f"Thread 2 write result: {result.modified_count} modified")
- sleep(5)
- except Exception as e:
- print(f"Thread 2 unexpected error: {e}")
- if __name__ == "__main__":
- print("Starting threads...")
- Thread(target=first_transaction).start()
- Thread(target=second_transaction).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement