xref: /aosp_15_r20/external/grpc-grpc/examples/python/interceptors/async/README.md (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1# gRPC Python Async Interceptor Example
2
3This example demonstrate the usage of Async interceptors and context propagation using [contextvars](https://docs.python.org/3/library/contextvars.html#module-contextvars).
4
5## When to use contextvars
6
7`Contextvars` can be used to propagate context in a same thread or coroutine, some example usage include:
8
91. Propagate from interceptor to another interceptor.
102. Propagate from interceptor to the server handler.
113. Propagate from client to server.
12
13## How does this example works
14
15This example have the following steps:
161. Generate RPC ID on client side and propagate to server using `metadata`.
17    * `contextvars` can be used here if client and server is running in a same coroutine (or same thead for Sync).
182. Server interceptor1 intercept the request, it checks `rpc_id_var` and decorate it with it's tag `Interceptor1`.
193. Server interceptor2 intercept the request, it checks `rpc_id_var` and decorate it with it's tag `Interceptor2`.
204. Server handler receives the request with `rpc_id_var` decorated by both interceptor1 and interceptor2.
21
22## How to run this example
23
241. Start server: `python3 -m async_greeter_server_with_interceptor`
252. Start client: `python3 -m async_greeter_client`
26
27### Expected outcome
28
29* On client side, you should see logs similar to:
30
31```
32Sending request with rpc id: 59ac966558b3d7d11a06bd45f1a0f89d
33Greeter client received: Hello, you!
34```
35
36* On server side, you should see logs similar to:
37
38```
39INFO:root:Starting server on [::]:50051
40INFO:root:Interceptor1 called with rpc_id: default
41INFO:root:Interceptor2 called with rpc_id: Interceptor1-59ac966558b3d7d11a06bd45f1a0f89d
42INFO:root:Handle rpc with id Interceptor2-Interceptor1-59ac966558b3d7d11a06bd45f1a0f89d in server handler.
43```
44