ASGI Lifespan

2.1.0 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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())

view raw JSON →