ormar
ormar copied to clipboard
Issues with latest fastapi connection example app (lifespan, missing type)
Describe the bug
The latest ormar docs about connecting while using fastapi have two issues for me:
-
AsyncIteratoris not imported fromtyping, but that is an easy fix - the bigger issue is that
lifespanneeds to be a decorator that handles the fastapi app object, not the ormar config:
ERROR: Traceback (most recent call last):
File "/home/foo/bar/api/.venv/lib/python3.11/site-packages/starlette/routing.py", line 732, in lifespan
async with self.lifespan_context(app) as maybe_state:
TypeError: 'function' object does not support the asynchronous context manager protocol
I fixed this by returning the decorator with the config:
def get_lifespan(config):
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
if not config.database.is_connected:
await config.database.connect()
yield
if config.database.is_connected:
await config.database.disconnect()
return lifespan
app = FastAPI(lifespan=get_lifespan(base_ormar_config))
And it works so far.
I'll just skip the other questions because it is a fairly clear documentation-only issue.