Debian Codegraph @

docs/source/reference-core/contextvar-example.py

raw
1 import random
2 import trio
3 import contextvars
4
5 request_info = contextvars.ContextVar("request_info")
6
7
8 # Example logging function that tags each line with the request identifier.
9 def log(msg):
10 # Read from task-local storage:
11 request_tag = request_info.get()
12
13 print(f"request {request_tag}: {msg}")
14
15
16 # An example "request handler" that does some work itself and also
17 # spawns some helper tasks to do some concurrent work.
18 async def handle_request(tag):
19 # Write to task-local storage:
20 request_info.set(tag)
21
22 log("Request handler started")
23 await trio.sleep(random.random())
24 async with trio.open_nursery() as nursery:
25 nursery.start_soon(concurrent_helper, "a")
26 nursery.start_soon(concurrent_helper, "b")
27 await trio.sleep(random.random())
28 log("Request received finished")
29
30
31 async def concurrent_helper(job):
32 log(f"Helper task {job} started")
33 await trio.sleep(random.random())
34 log(f"Helper task {job} finished")
35
36
37 # Spawn several "request handlers" simultaneously, to simulate a
38 # busy server handling multiple requests at the same time.
39 async def main():
40 async with trio.open_nursery() as nursery:
41 for i in range(3):
42 nursery.start_soon(handle_request, i)
43
44
45 trio.run(main)