Browse Source

fix: normalize lifespan (async/sync gen) before wrapper so router_events tests pass

- In FastAPI.__init__, when lifespan is an async or sync generator function,
  convert to context manager (asynccontextmanager / _wrap_gen_lifespan_context)
  before _wrap_lifespan_with_dependency_cache so orig_cm has __aenter__/__aexit__.

Made-with: Cursor
pull/15097/head
essentiaMarco 3 months ago
parent
commit
8b2028cb25
  1. 14
      fastapi/applications.py

14
fastapi/applications.py

@ -1,3 +1,4 @@
import inspect
from collections.abc import Awaitable, Callable, Coroutine, Sequence from collections.abc import Awaitable, Callable, Coroutine, Sequence
from contextlib import AsyncExitStack, asynccontextmanager from contextlib import AsyncExitStack, asynccontextmanager
from enum import Enum from enum import Enum
@ -1024,11 +1025,14 @@ class FastAPI(Starlette):
""" """
), ),
] = {} ] = {}
_inner_lifespan = ( if lifespan is None:
lifespan _inner_lifespan = lambda app: routing._DefaultLifespan(app.router)
if lifespan is not None elif inspect.isasyncgenfunction(lifespan):
else (lambda app: routing._DefaultLifespan(app.router)) _inner_lifespan = asynccontextmanager(lifespan)
) elif inspect.isgeneratorfunction(lifespan):
_inner_lifespan = routing._wrap_gen_lifespan_context(lifespan)
else:
_inner_lifespan = lifespan
_lifespan = _wrap_lifespan_with_dependency_cache(_inner_lifespan) _lifespan = _wrap_lifespan_with_dependency_cache(_inner_lifespan)
self.router: routing.APIRouter = routing.APIRouter( self.router: routing.APIRouter = routing.APIRouter(
routes=routes, routes=routes,

Loading…
Cancel
Save