Idea of LifespanManager
to have multiple lifespans in app
#9397
uriyyo
started this conversation in
Show and tell
Replies: 2 comments
-
@uriyyo You could use this import contextlib
from collections.abc import AsyncIterator, Callable, Sequence
from contextlib import AbstractAsyncContextManager
from fastapi import FastAPI
@contextlib.asynccontextmanager
async def _manager(
app: FastAPI,
lifespans: Sequence[Callable[[FastAPI], AbstractAsyncContextManager[None]]],
) -> AsyncIterator[None]:
exit_stack = contextlib.AsyncExitStack()
async with exit_stack:
for lifespan in lifespans:
await exit_stack.enter_async_context(lifespan(app))
yield
class Lifespans:
def __init__(
self,
lifespans: Sequence[Callable[[FastAPI], AbstractAsyncContextManager[None]]],
) -> None:
self.lifespans = lifespans
def __call__(self, app: FastAPI) -> AbstractAsyncContextManager[None]:
self.app = app
return _manager(app, lifespans=self.lifespans)
@contextlib.asynccontextmanager
async def one(app: FastAPI) -> AsyncIterator[None]:
print("One")
yield
print("End One")
@contextlib.asynccontextmanager
async def two(app: FastAPI) -> AsyncIterator[None]:
print("Two")
yield
print("End Two")
app = FastAPI(lifespan=Lifespans([one, two])) |
Beta Was this translation helpful? Give feedback.
0 replies
-
Thanks both for your help and inspiration! I wouldnt have found my solution without you...
I confess I did not run this example, but the code is ripped from a working version that I am using....so apologies for any oversights. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The old approach with
on_startup
,on_shutdown
is deprecated and will be removed in future versions ofstarlette
.The new
lifespan
approach has a small issue in that you can't have multiplelifespans
defined. It's great to have a separate lifespan for db connection, cache connection, .etc.I have created library called fastapi-lifespan-manager which aimed to fixed this issue.
I am happy to open PR to add this feature to
fastapi
cause the library is pretty small itself.Usage example:
Beta Was this translation helpful? Give feedback.
All reactions