First check
Description
Starlette added support for the lifespan context function in 0.13.5. It's not well documented, but the code does suggest:
# The lifespan context function is a newer style that replaces
# on_startup / on_shutdown handlers. Use one or the other, not both.
For my purposes, it's much more convenient to use a (async)contextmanager for the startup and shutdown events of my application. It would be nice to have the option
The solution you would like
I'd like an easier way, and one that's officially supported, to use the lifespan context function.
from fastapi import FastAPI
async def lifespan(app):
print("startup")
async with SomeResource():
yield
print("shutdown")
app = FastAPI(lifespan=lifespan)
or
from fastapi import FastAPI
app = FastAPI()
@app.lifespan
async def lifespan(app):
print("startup")
async with SomeResource():
yield
print("shutdown")
Describe alternatives you've considered
I can already accomplish this simply by doing:
from fastapi import FastAPI
async def lifespan(app):
print("startup")
async with SomeResource():
yield
print("shutdown")
app = FastAPI()
app.router.lifespan_context = lifespan
however this is not officially supported and would likely break if accidentally using app.on_event in addition.
One could also do nasty stuff with __aenter__ and __aexit__:
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup()
print("startup")
app.state.resource = SomeResource()
await app.state.resource.__aenter__()
@app.on_event("shutdown")
async def startup()
print("shutdown")
await app.state.resource.__aexit__(None, None, None)
but that seems quite ugly to me.
Environment
- OS: Linux
- FastAPI Version: 0.63.0
- Python version: 3.8.5
First check
Description
Starlette added support for the lifespan context function in 0.13.5. It's not well documented, but the code does suggest:
For my purposes, it's much more convenient to use a (async)contextmanager for the startup and shutdown events of my application. It would be nice to have the option
The solution you would like
I'd like an easier way, and one that's officially supported, to use the lifespan context function.
or
Describe alternatives you've considered
I can already accomplish this simply by doing:
however this is not officially supported and would likely break if accidentally using
app.on_eventin addition.One could also do nasty stuff with
__aenter__and__aexit__:but that seems quite ugly to me.
Environment