Starlette: Startup / Shutdown events

Created on 20 Sep 2018  路  8Comments  路  Source: encode/starlette

Refs https://github.com/django/asgiref/pull/63

Add @app.startup and @app.shutdown decorators that call into code on lifespan startup/shutdown.

Eg...

app = Starlette()

@app.startup
async def initialize_database_connection_pool():
    ...

@app.shutdown
async def close_database_connection():
    ...

You'll be able to add multiple startup/shutdown events.

All 8 comments

Thanks for that! I'm assuming these decorators will reference the app inside the decorated function somehow, so various lifetime objects can be attached directly to it?

On a related note, is there a way to access a "parent" app by its "children"? So e.g. if I do:

app = Starlette()

foo = Router([
    Path('/bar', FooBar),
    Path('/baz', FooBaz)
])
app.mount('/foo', foo)

Do FooBar and FooBaz have access to app (and foo) in some way? And any attached lifetime objects? The idea is that we could instantiate a database connection on the top app and reuse it below.

mounted applications will have lifetime events passed to them.

For stuff like database connections you鈥檇 probably have a global connection pool object, and use it from both places.

Middleware around parent applications would be able to pass context down to their children too, which might also be helpful here. (Docs and better support for that is incoming)

would @app.shutdown be a good place to shutdown websockets that are in a while true loop?

Use the websocket.disconnect message to handle that case. (Servers should disconnect connections and allow a short timeout for task completion prior to shutdown.)

Sorry, just starting out, ( and newish to python ) but I found this issue from #63 and i'm wondering if it's possible to use a database (leveraging https://github.com/MagicStack/asyncpg for example) with starlette? Or do we have to wait until 1.0?

@dfcarpenter I got your back here.

Upgrade to the latest uvicorn and latest starlette, for nice startup/cleanup support.

https://www.starlette.io/events/

There's workarounds before now, but this is really what we want for doing things like initializing a database connection pool within an async context.

awesome thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dgrahn picture dgrahn  路  4Comments

kouohhashi picture kouohhashi  路  3Comments

PeriGK picture PeriGK  路  5Comments

hyperknot picture hyperknot  路  6Comments

Immortalin picture Immortalin  路  3Comments