It's a peach


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


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(scope, info, request):
    print("Running startup handler")

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

app = Application(
), port=9009)

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

app = Application()

We could have used a decorator instead.

app = Application()

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

Handler Parameters


The scope parameter contains the unmodified ASGI scope defined here.

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


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

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


The request is another unmodified piece of ASGI data, which contains the content of the startup or shutdown event. This is also not particularly useful, and is provided for completeness

What next?

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