Skip to content

Commit 589da38

Browse files
authored
Close generators on client abort with sanic datastar_response (#4)
1 parent 0a666dd commit 589da38

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

src/datastar_py/sanic.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
from collections.abc import Awaitable, Collection, Mapping
4+
from contextlib import aclosing, closing
45
from functools import wraps
56
from inspect import isasyncgen, isgenerator
67
from typing import Any, Callable, ParamSpec, Union
@@ -74,15 +75,19 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> DatastarResponse | None:
7475
if isasyncgen(r):
7576
request = args[0]
7677
response = await request.respond(response=DatastarResponse())
77-
async for event in r:
78-
await response.send(event)
78+
# Make sure when the client cancels the stream clean up the generator now
79+
# Without the aclosing manager it would happen at garbage collection
80+
async with aclosing(r) as ait:
81+
async for event in ait:
82+
await response.send(event)
7983
await response.eof()
8084
return None
8185
if isgenerator(r):
8286
request = args[0]
8387
response = await request.respond(response=DatastarResponse())
84-
for event in r:
85-
await response.send(event)
88+
with closing(r) as it:
89+
for event in it:
90+
await response.send(event)
8691
await response.eof()
8792
return None
8893
return DatastarResponse(r)

0 commit comments

Comments
 (0)