async def solve_generator(*, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any]) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm)
async def solve_generator(*, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any]) -> Any: if inspect.isgeneratorfunction(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif inspect.isasyncgenfunction(call): cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm)
async def add_session_to_request(request: Request, call_next): """Middleware which injects a new sqla session into every request. Handles creation of session, as well as commit, rollback, and closing of session. Usage:: import fastapi_sqla from fastapi import FastApi app = FastApi() fastapi_sqla.setup(app) # includes middleware @app.get("/users") def get_users(session: fastapi_sqla.Session = Depends()): return session.execute(...) # use your session here """ async with contextmanager_in_threadpool(open_session()) as session: request.scope[_SESSION_KEY] = session response = await call_next(request) if response.status_code >= 400: # If ever a route handler returns an http exception, we do not want the # session opened by current context manager to commit anything in db. loop = asyncio.get_running_loop() await loop.run_in_executor(None, session.rollback) return response
async def solve_generator(*, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any]) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): if not inspect.isasyncgenfunction(call): # asynccontextmanager from the async_generator backfill pre python3.7 # does not support callables that are not functions or methods. # See https://github.com/python-trio/async_generator/issues/32 # # Expand the callable class into its __call__ method before decorating it. # This approach will work on newer python versions as well. call = getattr(call, "__call__", None) cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm)