Skip to content

Lifespan

Lifespan events occur when the server starts up and shuts down.

On startup they can be used for initialization, or for starting long running tasks. On shutdown they can clean up resources and provide graceful termination.

You can find the ASGI documentation here.

The source code for the following example can be found here (and here here with typing).

Handlers

The following code creates an application with a startup and shutdown handler.

The handlers simply log a message.

import asyncio
import logging

import uvicorn

from bareasgi import Application, text_writer

async def on_startup(request):
    print("Running startup handler")

async def on_shutdown(request):
    print("Running shutdown handler")

app = Application(
    startup_handlers=[on_startup],
    shutdown_handlers=[on_shutdown]
)

uvicorn.run(app, port=9009)

We can add the handlers at any point before the application starts (or stops for shutdown handlers).

app = Application()
app.startup_handlers.append(on_startup)
app.shutdown_handlers.append(on_shutdown)

We could have used a decorator instead.

app = Application()

@app.on_startup
async def on_startup(request):
    print("Running startup handler")

LifspanRequest

The request parameter is of type LifespanRequest.

This has the following fields

Scope

The scope field contains the unmodified ASGI scope defined here.

It doesn't contain much that's useful, but I pass it for completeness.

Info

The info field contains the data that is shared across the application.

This is typically used to retrieve configuration, and store resources.

What next?

Either go back to the table of contents or go to the background tasks tutorial.