Debian Codegraph @

docs/source/reference-core/thread-contextvars-example.py

raw
1 import contextvars
2 import time
3
4 import trio
5
6 request_state = contextvars.ContextVar("request_state")
7
8 # Blocking function that should be run on a thread
9 # It could be reading or writing files, communicating with a database
10 # with a driver not compatible with async / await, etc.
11 def work_in_thread(msg):
12 # Only use request_state.get() inside the worker thread
13 state_value = request_state.get()
14 current_user_id = state_value["current_user_id"]
15 time.sleep(3) # this would be some blocking call, like reading a file
16 print(f"Processed user {current_user_id} with message {msg} in a thread worker")
17 # Modify/mutate the state object, without setting the entire
18 # contextvar with request_state.set()
19 state_value["msg"] = msg
20
21
22 # An example "request handler" that does some work itself and also
23 # spawns some helper tasks in threads to execute blocking code.
24 async def handle_request(current_user_id):
25 # Write to task-local storage:
26 current_state = {"current_user_id": current_user_id, "msg": ""}
27 request_state.set(current_state)
28
29 # Here the current implicit contextvars context will be automatically copied
30 # inside the worker thread
31 await trio.to_thread.run_sync(work_in_thread, f"Hello {current_user_id}")
32 # Extract the value set inside the thread in the same object stored in a contextvar
33 new_msg = current_state["msg"]
34 print(
35 f"New contextvar value from worker thread for user {current_user_id}: {new_msg}"
36 )
37
38
39 # Spawn several "request handlers" simultaneously, to simulate a
40 # busy server handling multiple requests at the same time.
41 async def main():
42 async with trio.open_nursery() as nursery:
43 for i in range(3):
44 nursery.start_soon(handle_request, i)
45
46
47 trio.run(main)