Lifespan signals (low-level)
Tip
Developers are advised to prefer asynchronous context managers. Using signals directly is fully supported, and until v0.2.0
this was the only way to use this plugin — the only downside is that it is a more low-level way to use it.
Before you start¶
This low-level approach uses ASGI lifespan signals directly. The disadvantage is that the developer has to figure out where to store the global shared state. Prefer the more modern approach via context manager — the global state will be managed by the ASGI server.
Example use case for lifespan signals¶
Consider a Django application named library
. This application retrieves book information from an external API using HTTPX. To ensure efficient utilization of network resources (e.g., connection pooling, see: https://www.python-httpx.org/advanced/#why-use-a-client), we intend to use the HTTPX client.
Typehinting¶
Firstly, we're going to define a Protocol for typehinting.
This Protocol (HTTPXAppConfig
) provides an explicit interface for a request that contains a reference to an instance of httpx.AsyncClient
in its state
dictionary.
types.py | |
---|---|
Signal receivers¶
Next, we create receivers for lifespan signals. A startup receiver that creates an instance of the HTTPX client, and a shutdown receiver that closes the client.
Connect the receivers to the lifespan signals:
Access shared state in view¶
Now we can access the HTTPX client instance in our view: