-
I have a subscription function that continuously yields values. Here's a simplified example of my code: @strawberry.type
class Subscription:
@strawberry.subscription
async def counter(self) -> AsyncGenerator[int, None]:
for value in itertools.count():
yield value
print(value)
await asyncio.sleep(1) I would like to be able to detect when the browser closes the connection, and if the connection is closed, I want to print a message like "connection closed" from inside the counter function. Is there a way to achieve this with Strawberry or otherwise? Uvicorn runs the app. Strawberry is exposed to clients via FastAPI: fastapi_app.add_websocket_route("/graphql", GraphQL(strawberry.Schema(..., subscription=Subscription))) I would greatly appreciate any guidance or suggestions. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
When the browser closes the connection, the subscription handler cancels the counter task (if I am not mistaken, here) As outlined in Python's Task Cancellation documentation.
The following modified code works for me. @strawberry.type
class Subscription:
@strawberry.subscription
async def counter(self) -> AsyncGenerator[int, None]:
try:
for value in itertools.count():
yield value
print(value)
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled")
raise |
Beta Was this translation helpful? Give feedback.
When the browser closes the connection, the subscription handler cancels the counter task (if I am not mistaken, here)
As outlined in Python's Task Cancellation documentation.
The following modified code works for me.