Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ResourceWarning from DataBody.__aiter__ #301

Closed
graingert opened this issue Dec 18, 2023 · 1 comment · Fixed by #302
Closed

ResourceWarning from DataBody.__aiter__ #301

graingert opened this issue Dec 18, 2023 · 1 comment · Fixed by #302

Comments

@graingert
Copy link
Contributor

from quart-trio I get a:

ResourceWarning: Async generator 'quart.wrappers.response.DataBody.__aiter__.<locals>._aiter' was garbage collected before it had been exhausted. Surround its use in 'async with aclosing(...):' to ensure that it gets cleaned up as soon as you're done using it.

Environment:

  • Python version:
  • Quart version:
@pgjones
Copy link
Member

pgjones commented Feb 11, 2024

I'm also unsure how to test this, however I've an alternative fix,

diff --git a/src/quart/wrappers/response.py b/src/quart/wrappers/response.py
index 9460c2e..6b0b364 100644
--- a/src/quart/wrappers/response.py
+++ b/src/quart/wrappers/response.py
@@ -70,18 +70,20 @@ class DataBody(ResponseBody):
         self.data = data
         self.begin = 0
         self.end = len(self.data)
+        self.iter: AsyncGenerator[bytes, None]
 
     async def __aenter__(self) -> DataBody:
+        async def _aiter() -> AsyncGenerator[bytes, None]:
+            yield self.data[self.begin : self.end]
+
+        self.iter = _aiter()
         return self
 
     async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
-        pass
+        await self.iter.aclose()
 
     def __aiter__(self) -> AsyncIterator:
-        async def _aiter() -> AsyncGenerator[bytes, None]:
-            yield self.data[self.begin : self.end]
-
-        return _aiter()
+        return self.iter
 
     async def make_conditional(self, begin: int, end: int | None) -> int:
         self.begin = begin

What do you think of this? I prefer it as it is more similar to the IterableBody

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants