Created
August 13, 2021 18:34
-
-
Save frennkie/9b464907a27646120b78cac9434c0e22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@app.get("/sse/stream") | |
async def stream(req: Request, channel: str = "default", redis: Redis = Depends(depends_redis)): | |
# return EventSourceResponse(subscribe(channel, redis)) | |
async def event_publisher(): | |
_log.info(f"Subscribing for client {req.client}") | |
(channel_subscription,) = await redis.subscribe(channel=Channel(channel, False)) | |
try: | |
while True: | |
disconnected = await req.is_disconnected() | |
if disconnected: | |
_log.info(f"Disconnecting client {req.client}") | |
_log.info(f"Unsubscribing for client {req.client}") | |
(channel_unsubscription,) = await redis.unsubscribe(channel=Channel(channel, False)) | |
break | |
while await channel_subscription.wait_message(): | |
yield {"event": "message", "data": await channel_subscription.get(encoding='utf-8')} | |
_log.info(f"Disconnected from client {req.client}") | |
_log.info(f"Unsubscribing for client {req.client}") | |
(channel_unsubscription,) = await redis.unsubscribe(channel=Channel(channel, False)) | |
except asyncio.CancelledError as e: | |
_log.info(f"Disconnected from client (via refresh/close) {req.client}") | |
# Do any other cleanup, if any | |
_log.info(f"Unsubscribing for client {req.client}") | |
(channel_unsubscription,) = await redis.unsubscribe(channel=Channel(channel, False)) | |
raise e | |
return EventSourceResponse(event_publisher()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment