Advertisement
Guest User

WriteConflicts in mongo

a guest
Nov 4th, 2024
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | Source Code | 0 0
  1. from pymongo import MongoClient, ReadPreference, WriteConcern
  2. from pymongo.read_concern import ReadConcern
  3. from time import sleep
  4. from threading import Thread
  5. from dotenv import dotenv_values
  6.  
  7. config = dotenv_values(".env")
  8.  
  9. def first_transaction():
  10.     client = MongoClient(config["MONGO_URI"])
  11.     db = client["test"]
  12.     collection = db["transaction_test"]
  13.    
  14.     sleep(5)
  15.  
  16.     while True:
  17.         try:
  18.             with client.start_session() as session:
  19.                 session.start_transaction(
  20.                     read_concern=ReadConcern(level="snapshot"),
  21.                     write_concern=WriteConcern(w="majority"),
  22.                     read_preference=ReadPreference.PRIMARY
  23.                 )
  24.  
  25.                 doc = collection.find_one({"id": 1}, session=session)
  26.                 print(f"Thread 1 read value: {doc.get('value') if doc else None}")
  27.                 sleep(10)
  28.                 print("Thread 1 attempting write")
  29.                 result = collection.update_one({"id": 1}, {"$inc": {"value": -1}}, session=session)
  30.                 print(f"Thread 1 write result: {result.modified_count} modified")
  31.  
  32.                 session.commit_transaction()
  33.                 print("Thread 1 committed transaction")
  34.            
  35.             sleep(5)
  36.         except Exception as e:
  37.             print(f"Thread 1 unexpected error: {e}")
  38.  
  39. def second_transaction():
  40.     client = MongoClient(config["MONGO_URI"])
  41.     db = client["test"]
  42.     collection = db["transaction_test"]
  43.  
  44.     while True:
  45.         try:
  46.             print("Thread 2 attempting write")
  47.             result = collection.update_one({"id": 1}, {"$inc": {"value": 2}})
  48.             print(f"Thread 2 write result: {result.modified_count} modified")                
  49.             sleep(5)
  50.         except Exception as e:
  51.             print(f"Thread 2 unexpected error: {e}")
  52.  
  53. if __name__ == "__main__":    
  54.     print("Starting threads...")
  55.     Thread(target=first_transaction).start()
  56.     Thread(target=second_transaction).start()
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement