@@ -45,11 +45,56 @@ class State(TypedDict):
4545
4646@asynccontextmanager  
4747async  def  lifespan (app : FastAPI ) ->  AsyncGenerator [State , None ]:
48-     """A  lifespan context manager that setup `FastSQLA` when opened . 
48+     """Use `fastsqla. lifespan` to set up SQLAlchemy . 
4949
50-     This async context manager must be used to setup SQLAlchemy. 
50+     In an ASGI application, [lifespan events](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) 
51+     are used to communicate startup & shutdown events. 
5152
52-     TBD 
53+     The [`lifespan`](https://fastapi.tiangolo.com/advanced/events/#lifespan) parameter of 
54+     the `FastAPI` app can be set to a context manager. That context manager is 
55+     opened when app starts and closed when app stops. 
56+ 
57+     In order for `FastSQLA` to setup `SQLAlchemy` before the app is started, set 
58+     `lifespan` parameter to `fastsqla.lifespan`: 
59+ 
60+     ```python 
61+     from fastapi import FastAPI 
62+     from fastsqla import lifespan 
63+ 
64+ 
65+     app = FastAPI(lifespan=lifespan) 
66+     ``` 
67+ 
68+     If you need to open more than one lifespan context, create an async context manager 
69+     function to open as many lifespans as needed and set it as the lifespan of the app. 
70+     Use an [AsyncExitStack][contextlib.AsyncExitStack] to open multiple lifespan contexts: 
71+ 
72+     ```python 
73+     from collections.abc import AsyncGenerator 
74+     from contextlib import asynccontextmanager 
75+ 
76+     from fastapi import FastAPI 
77+     from fastsqla import lifespan as fastsqla_lifespan 
78+     from this_other_library import another_lifespan 
79+ 
80+ 
81+     @asynccontextmanager 
82+     async def lifespan(app:FastAPI) -> AsyncGenerator[dict, None]: 
83+         async with AsyncExitStack() as stack: 
84+             yield { 
85+                 **stack.enter_async_context(lifespan(app)), 
86+                 **stack.enter_async_context(another_lifespan(app)), 
87+             } 
88+ 
89+ 
90+     app = FastAPI(lifespan=lifespan) 
91+     ``` 
92+ 
93+     To know more about lifespan protocol: 
94+ 
95+     * [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) 
96+     * [Use Lifespan State instead of `app.state`](https://github.com/Kludex/fastapi-tips?tab=readme-ov-file#6-use-lifespan-state-instead-of-appstate) 
97+     * [FastAPI lifespan documentation](https://fastapi.tiangolo.com/advanced/events/): 
5398    """ 
5499    prefix  =  "sqlalchemy_" 
55100    sqla_config  =  {k .lower (): v  for  k , v  in  os .environ .items ()}
0 commit comments