Registry / web-framework / asgi-lifespan

asgi-lifespan

JSON →
library2.1.0pypypi✓ verified 25d ago

asgi-lifespan is a Python library that enables programmatic control over the startup and shutdown lifecycle events of ASGI applications. It's primarily used for testing or mocking ASGI apps without requiring a full ASGI server, facilitating resource initialization and cleanup during development and CI. The current version is 2.1.0, with releases typically driven by new features, bug fixes, or Python version support.

pip install asgi-lifespan
INSTALL
IMPORT
SIG · ASGI-LIFESPAN
A
asgi-lifespan
web-frameworkpythonv2.1.0
Install
1.6s avg
Import
17ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.016s · 18MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.018s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

LifespanManager
from asgi_lifespan import LifespanManager

This quickstart demonstrates how to use `LifespanManager` to programmatically trigger the startup and shutdown events of an ASGI application. It defines a simple Starlette app with a lifespan context manager that prints messages. Running this code will execute the startup logic, proceed through the `async with` block, and then execute the shutdown logic, all without needing to spin up a separate ASGI server. This pattern is particularly useful for testing.

import asyncio from contextlib import asynccontextmanager from asgi_lifespan import LifespanManager from starlette.applications import Starlette from starlette.responses import PlainTextResponse # An example ASGI application with a lifespan context manager @asynccontextmanager async def lifespan(app: Starlette): print("ASGI app startup: Initializing resources...") yield print("ASGI app shutdown: Cleaning up resources...") app = Starlette(lifespan=lifespan) @app.route("/") async def homepage(request): return PlainTextResponse("Hello, world!") async def run_lifespan_example(): print("Starting LifespanManager...") async with LifespanManager(app) as manager: print("LifespanManager active, app is ready.") # In a real test, you would now use an ASGI client like httpx.AsyncClient(app=manager.app) # to send requests and interact with the 'started' application. # For this example, we'll just show the lifespan events. print("LifespanManager exited, app is shut down.") if __name__ == "__main__": asyncio.run(run_lifespan_example())
Debug
Known issues
breakingVersion 2.0.0 of `asgi-lifespan` dropped support for Python 3.6. Users on Python 3.6 must remain on `asgi-lifespan<2.0.0` or upgrade their Python interpreter.
fix
Upgrade your Python environment to 3.7 or newer. If not possible, pin `asgi-lifespan<2.0.0`.
affects: >=2.0.0
breakingThe `Lifespan` class and `LifespanMiddleware` were removed in earlier major versions (specifically 1.0.0) in favor of the `LifespanManager` asynchronous context manager. Code using the old API will break.
fix
Migrate your code to use `LifespanManager` as an asynchronous context manager, as shown in the quickstart example.
affects: >=1.0.0
gotchaIf you encounter the error `LifespanNotSupported` or `ASGI 'lifespan' protocol appears unsupported`, it typically means the wrapped ASGI application did not correctly implement the ASGI lifespan protocol, or an unhandled exception occurred during its startup or shutdown phase. `asgi-lifespan` detects this if the app calls `send()` before `receive()` for the first time, or raises an exception during startup.
fix
Ensure your ASGI application fully conforms to the ASGI lifespan specification (e.g., sending `lifespan.startup.complete` or `lifespan.shutdown.complete` events). If using an ASGI server like Uvicorn, running with `--lifespan on` might reveal the underlying error during startup/shutdown.
affects: All versions
gotchaWhen using `LifespanManager` in conjunction with an ASGI test client (e.g., `httpx.AsyncClient`), it's crucial to pass `manager.app` (not just `app`) to the client's `ASGITransport`. This ensures that any state created by the lifespan events is correctly propagated and available to subsequent request/response handling within the client's scope.
fix
Modify your test client initialization to `httpx.AsyncClient(transport=httpx.ASGITransport(app=manager.app))`.
affects: All versions
breakingThe test script failed with a `ModuleNotFoundError` for `starlette`. This indicates a missing dependency required for the test script to run, rather than an issue directly with `asgi-lifespan`'s API or behavior.
fix
Ensure all necessary dependencies, specifically `starlette` (or any other module mentioned in a `ModuleNotFoundError`), are installed in the test environment (e.g., `pip install starlette`). Review the script's `import` statements to identify all required packages.
affects: All versions
gotchaThe test script or your application requires 'starlette', which is not installed. While `asgi-lifespan` itself does not have a direct hard dependency on `starlette`, it is commonly used in conjunction with ASGI frameworks like Starlette. This error indicates a missing dependency in your environment for a component that `asgi-lifespan` might be interacting with or that the test script uses to demonstrate its functionality.
fix
Ensure 'starlette' is installed in your environment by running `pip install starlette`.
affects: All versions
Errors
Common errors & fixes
[INFO] ASGI 'lifespan' protocol appears unsupported.
This message indicates that the ASGI server does not support the lifespan protocol, which is used for startup and shutdown events.
fix
Ensure that the ASGI server and application both support the lifespan protocol. If using Uvicorn, you can run it with the `--lifespan on` option to enable lifespan support.
AttributeError: module 'asgi_lifespan' has no attribute 'LifespanManager'
This error occurs when attempting to access 'LifespanManager' from the 'asgi_lifespan' module, which may not be available in the installed version.
fix
Ensure you have the correct version of 'asgi-lifespan' installed by running 'pip install asgi-lifespan'.
ImportError: cannot import name 'LifespanManager' from 'asgi_lifespan'
This error occurs when the 'LifespanManager' class is not found in the 'asgi_lifespan' module, possibly due to an outdated or incompatible version.
fix
Update 'asgi-lifespan' to the latest version by running 'pip install --upgrade asgi-lifespan'.
ASGI 'lifespan' protocol appears unsupported.
This message typically originates from an ASGI server (like Uvicorn) when the ASGI application (e.g., FastAPI, Starlette) either does not correctly implement the ASGI lifespan protocol or an exception occurs during its startup/shutdown events, leading the server to believe the protocol is not supported.
fix
Ensure your ASGI application properly defines and handles the lifespan protocol using an `asynccontextmanager` for startup and shutdown events. When testing with `asgi-lifespan`, wrap your application with `LifespanManager` to correctly trigger and manage these events, allowing you to debug any underlying issues in your app's lifespan handlers. You might also run your server with `--lifespan on` to get more detailed error logs if an exception is occurring within your application's lifespan events.
asgi_lifespan.errors.LifespanNotSupported: The application does not seem to support the lifespan protocol.
This error is raised by `asgi-lifespan`'s `LifespanManager` if the ASGI application it's wrapping does not correctly implement the ASGI lifespan protocol, specifically if the application calls `send()` before `receive()` during startup, or raises an exception before its first `receive()` call for a lifespan event.
Upgrade
Version history
2.1.0latest on PyPI · released Mar 28, 2023
Audit
Dependencies
pythonrequiredRequires Python 3.7 or newer.
Agent activity
24 hits · last 30 days
node
21
OpenAI (training)
1
Resources