Ist es überhaupt möglich, den Antworttyp zu überprüfen? Beispiel: < /p>
Code: Select all
_engine = create_async_engine(
f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{database}"
)
AsyncSessionFactory = async_sessionmaker(bind=_engine, expire_on_commit=False)
class DBSessionMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
request.state.db_session_factory = AsyncSessionFactory
request.state.active_session = None
response = await call_next(request)
debug_logger.debug(f'response type: {type(response)}') # always prints `StreamingResponse`
if request.state.active_session and not isinstance(response, StreamingResponse):
request.state.active_session.close()
return response
# get or create the sesson from the factory
async def get_db_session(request: Request) -> AsyncSession:
if hasattr(request.state, "active_session") and request.state.active_session:
session = request.state.active_session
elif hasattr(request.state, "db_session_factory"):
request.state.active_session = request.state.db_session_factory()
session = request.state.active_session
debug_logger.debug(f'session {id(session)} opened')
else:
session = AsyncSessionFactory()
return cast(AsyncSession, session)