show practical context var usage with - Request tracking in web applications - User…
- User
show practical context var usage with
- Request tracking in web applications
- User authentication state
- Transaction management
- Assistant
show practical context var usage with
Context variables are a powerful feature in Python (introduced in Python 3.7 via the contextvars module) that allow you to manage state specific to a particular context, especially in asynchronous environments. They are ideal for scenarios where you need to maintain state across different parts of an application without passing variables explicitly through function arguments.
Below are practical examples demonstrating how to use context variables for:
We'll use Python's contextvars module to illustrate these use cases.
When handling web requests, especially asynchronously, it's often necessary to track individual requests (e.g., for logging, debugging, or correlation across services). Context variables can help maintain a unique request ID that is accessible throughout the request lifecycle.
import contextvars
import asyncio
import uuid
import logging
# Configure logging to include the request_id from context
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Define a context variable for request ID
request_id_var = contextvars.ContextVar('request_id')
def get_logger():
request_id = request_id_var.get(None)
if request_id:
return logging.LoggerAdapter(logging.getLogger(__name__), {'request_id': request_id})
else:
return logging.getLogger(__name__)
async def handle_request():
# Assign a unique ID for the request
token = request_id_var.set(str(uuid.uuid4()))
logger = get_logger()
try:
logger.info("Handling request")
await process_data()
logger.info("Finished handling request")
finally:
# Reset the context variable to its previous state
request_id_var.reset(token)
async def process_data():
logger = get_logger()
logger.info("Processing data")
await asyncio.sleep(1) # Simulate asynchronous processing
logger.info("Data processed")
async def main():
# Simulate handling multiple requests concurrently
await asyncio.gather(
handle_request(),
handle_request(),
handle_request(),
)
if __name__ == '__main__':
asyncio.run(main())
2023-10-07 12:00:00,000 - INFO - Handling request
2023-10-07 12:00:00,001 - INFO - Handling request
2023-10-07 12:00:00,002 - INFO - Handling request
2023-10-07 12:00:00,001 - INFO - Processing data
2023-10-07 12:00:00,000 - INFO - Processing data
2023-10-07 12:00:00,002 - INFO - Processing data
2023-10-07 12:00:01,001 - INFO - Data processed
2023-10-07 12:00:01,000 - INFO - Data processed
2023-10-07 12:00:01,002 - INFO - Data processed
2023-10-07 12:00:01,001 - INFO - Finished handling request
2023-10-07 12:00:01,000 - INFO - Finished handling request
2023-10-07 12:00:01,002 - INFO - Finished handling request
contextvars.ContextVar: Defines a context variable request_id_var to store the request ID.handle_request: Assigns a unique UUID to request_id_var for each request and ensures it's reset after processing.get_logger: Retrieves the logger and attaches the current request_id to it for contextual logging.main: Simulates handling multiple requests concurrently using asyncio.gather.This setup ensures that each log entry is associated with the correct request, even when handling multiple requests simultaneously.
Maintaining the authentication state (i.e., the currently authenticated user) is crucial for authorization checks and personalized responses. Using context variables allows you to access the current user throughout the request processing without passing the user object around.
import contextvars
import asyncio
# Define a context variable for the current user
current_user_var = contextvars.ContextVar('current_user')
class User:
def __init__(self, user_id, name):
self.user_id = user_id
self.name = name
async def authenticate(user_id):
# Simulate authentication (e.g., database lookup)
await asyncio.sleep(0.1) # Simulate I/O operation
user = User(user_id, f"User{user_id}")
token = current_user_var.set(user)
return token
async def get_user_info():
user = current_user_var.get(None)
if user:
print(f"User Info: ID={user.user_id}, Name={user.name}")
else:
print("No user is currently authenticated.")
async def process_request(user_id):
token = await authenticate(user_id)
try:
await get_user_info()
# Further processing can access `current_user_var` as needed
finally:
# Reset the context variable after request processing
current_user_var.reset(token)
async def main():
await asyncio.gather(
process_request(1),
process_request(2),
process_request(3),
)
if __name__ == '__main__':
asyncio.run(main())
User Info: ID=1, Name=User1
User Info: ID=2, Name=User2
User Info: ID=3, Name=User3
current_user_var: A context variable to store the currently authenticated user.authenticate: Simulates user authentication and sets the current_user_var.get_user_info: Retrieves and prints information about the current user.process_request: Authenticates a user, processes the request, and ensures the context is reset afterward.main: Simulates processing multiple user requests concurrently.This approach ensures that each request thread has its own current_user_var, preventing data leakage between requests.
When working with database transactions, it's essential to manage the transaction state (e.g., the current database session) throughout the transaction lifecycle. Context variables can help track and access the current transaction context across various parts of the application.
import contextvars
import asyncio
# Define a context variable for the current transaction
current_transaction_var = contextvars.ContextVar('current_transaction')
class DatabaseSession:
def __init__(self, session_id):
self.session_id = session_id
self.active = True
async def commit(self):
print(f"Committing transaction {self.session_id}")
self.active = False
await asyncio.sleep(0.1) # Simulate I/O operation
async def rollback(self):
print(f"Rolling back transaction {self.session_id}")
self.active = False
await asyncio.sleep(0.1) # Simulate I/O operation
async def begin_transaction():
session = DatabaseSession(session_id=uuid.uuid4())
token = current_transaction_var.set(session)
print(f"Started transaction {session.session_id}")
return token
async def perform_db_operations():
session = current_transaction_var.get(None)
if session and session.active:
print(f"Performing DB operations in transaction {session.session_id}")
await asyncio.sleep(0.2) # Simulate DB operations
else:
print("No active transaction found.")
async def handle_transaction(success=True):
token = await begin_transaction()
try:
await perform_db_operations()
if success:
await current_transaction_var.get().commit()
else:
await current_transaction_var.get().rollback()
except Exception as e:
await current_transaction_var.get().rollback()
print(f"Exception occurred: {e}")
finally:
current_transaction_var.reset(token)
async def main():
await asyncio.gather(
handle_transaction(success=True),
handle_transaction(success=False),
)
if __name__ == '__main__':
import uuid
asyncio.run(main())
Started transaction 123e4567-e89b-12d3-a456-426614174000
Started transaction 123e4567-e89b-12d3-a456-426614174001
Performing DB operations in transaction 123e4567-e89b-12d3-a456-426614174000
Performing DB operations in transaction 123e4567-e89b-12d3-a456-426614174001
Committing transaction 123e4567-e89b-12d3-a456-426614174000
Rolling back transaction 123e4567-e89b-12d3-a456-426614174001
current_transaction_var: A context variable to store the current database transaction session.DatabaseSession: Simulates a database session with commit and rollback capabilities.begin_transaction: Starts a new transaction session and sets current_transaction_var.perform_db_operations: Accesses the current transaction and performs operations within it.handle_transaction: Manages the transaction lifecycle, committing or rolling back based on the success flag.main: Simulates handling multiple transactions concurrently, one succeeding and one failing.This setup ensures that each transaction is handled independently, with their respective sessions managed via context variables.
Context variables provide a clean and efficient way to manage context-specific data across different parts of an application, especially in asynchronous or multi-threaded environments. By leveraging the contextvars module in Python, you can:
These patterns improve code readability, maintainability, and reduce the risk of context leakage or state corruption in complex applications.
Not yet included in a published release.