ormar icon indicating copy to clipboard operation
ormar copied to clipboard

Issues with latest fastapi connection example app (lifespan, missing type)

Open inktrap opened this issue 1 year ago • 0 comments

Describe the bug

The latest ormar docs about connecting while using fastapi have two issues for me:

  • AsyncIterator is not imported from typing, but that is an easy fix
  • the bigger issue is that lifespan needs 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.

inktrap avatar Jun 20 '24 14:06 inktrap