Skip to content

Commit

Permalink
Bugfix hold a strong reference to background tasks
Browse files Browse the repository at this point in the history
Otherwise these tasks may be garbaged collected as per
https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
  • Loading branch information
pgjones committed May 19, 2024
1 parent 3508d9a commit 425f685
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/quart/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
NoReturn,
Optional,
overload,
Set,
TypeVar,
Union,
)
from urllib.parse import quote
from weakref import WeakSet

from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
Expand Down Expand Up @@ -315,7 +315,7 @@ def __init__(
self.after_websocket_funcs: dict[AppOrBlueprintKey, list[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.background_tasks: WeakSet[asyncio.Task] = WeakSet()
self.background_tasks: Set[asyncio.Task] = set()
self.before_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.before_websocket_funcs: dict[AppOrBlueprintKey, list[BeforeWebsocketCallable]] = (
defaultdict(list)
Expand Down Expand Up @@ -1324,6 +1324,7 @@ async def _wrapper() -> None:

task = asyncio.get_event_loop().create_task(_wrapper())
self.background_tasks.add(task)
task.add_done_callback(self.background_tasks.discard)

async def handle_background_exception(self, error: Exception) -> None:
await got_background_exception.send_async(
Expand Down Expand Up @@ -1714,7 +1715,7 @@ async def shutdown(self) -> None:
timeout=self.config["BACKGROUND_TASK_SHUTDOWN_TIMEOUT"],
)
except asyncio.TimeoutError:
await cancel_tasks(self.background_tasks) # type: ignore
await cancel_tasks(self.background_tasks)

try:
async with self.app_context():
Expand Down

0 comments on commit 425f685

Please sign in to comment.