The example apps don't show how to clean up connections
EliRibble opened this issue · comments
Eli Ribble commented
The example apps are great, thanks for those. However, they don't show how to clean up connections. For example, here's what I did in my app after reading the examples:
async def get_stream(request):
response = await aiohttp_sse.sse_response(request)
LOGGER.info("Starting streaming event connection")
async with response:
queue = asyncio.Queue()
def _cleanup(task):
LOGGER.info("Cleaning up connection")
request.app['streams'].remove(queue)
response.task.add_done_callback(_cleanup)
response.send('New client connection to stream')
request.app['streams'].add(queue)
while True:
payload = await queue.get()
response.send(payload)
queue.task_done()
LOGGER.info("Disconnecting streaming event connection")
response.stop_streaming()
return response
Nicolas Delaby commented
please make a pull request.
Nikolay Novik commented
good point, could be accomplished bit simpler, without knowing anything about task.add_done_callbacktask.add_done_callback
request.app['streams'].add(response)
try:
async with response:
response.send(payload)
await response.wait()
finally:
request.app['streams']. remove(response)
return response
or dedicated context manager.
I think queue could be removed too, since you can share response
between coroutines and do response.send
from there.
Eli Ribble commented
You're probably right. I'll rework it and see if I can create a PR
Nikolay Novik commented
fixed via #40