Closed euri10 closed 10 months ago
This is not a bug and is actually mentioned in the docs, but I can see how it might be unexpected.
The reason for this is that the scope of the dependencies is tied to the handler function and not the response being sent.
The cleanup stage is executed after the handler function returns, but before the response is sent (in case of HTTP requests)
While this is in line with how other frameworks (FastAPI and Sanic as well afaik) handle it, I think ideally, you'd be able to define this scope yourself and change the default behaviour. We could revisit this when we do the DI overhaul.
Currently, the only proper solution would be to manage the connection inside the generator yourself, something like:
async def get_connection(state: State) -> AsyncGenerator[Connection, None]:
pool: Pool = state.dbpool
async with pool.acquire() as conn:
yield conn
@get("/stream", name="stream")
async def stream(state: State) -> ServerSentEvent:
async def stream_generator(pool: Pool) -> None:
async with pool.acquire() as conn:
await asyncio.sleep(1)
r = await conn.execute("select randon()")
yield ServerSentEventMessage(data=r)
return ServerSentEvent(stream_generator(state.pool))
Closing this for now as it's expected behaviour and there's nothing we can do about it at the moment.
ok got it, I didn't think about getting the connection that way but this is exactly how I do it in guards :man_facepalming:
I'm fine doing it this way, I just dont know given the stream can last a while if there wont be timeout issues but I guess testing it will probably be the best answer
Description
I would have expect this code to be ok, however it seems like whe inside the generator I try to access the db the connection has already been released to the pool. So I'm not sure if this classifies as a bug, ie shoul the db conneciton last the time of the stream response or not, If it is not then it looks like to me it's kind of impossible to fetch db inside a generator that will be streamed, and I have not been able to find a way so far.
the trace fro the mvce below:
URL to code causing the issue
No response
MCVE
Steps to reproduce
Screenshots
Logs
No response
Litestar Version
2.5.0
Platform