From 85f35e560f4e6707c598fbdf15ff1ca5bae84b6d Mon Sep 17 00:00:00 2001 From: Kara Engelhardt Date: Tue, 19 Nov 2024 21:23:32 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Support=20async=20and=20sync=20s?= =?UTF-8?q?ervers=20in=20DocumentCollectionZipDownloadView?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A StreamingHttpResponse for ASGI needs an async iterator, else it will buffer everything in memory. Same with WSGI and sync iterators. This adds a StreamingHttpResponse interface that supports both --- src/filingcabinet/views.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/filingcabinet/views.py b/src/filingcabinet/views.py index 9ba8aee..f8472cf 100644 --- a/src/filingcabinet/views.py +++ b/src/filingcabinet/views.py @@ -189,6 +189,27 @@ def get_context_data(self, **kwargs): return context +async def as_aiter(iter): + for i in iter: + yield i + + +class ZipStreamResponse(StreamingHttpResponse): + @property + def streaming_content(self): + return self._sc + + @streaming_content.setter + def streaming_content(self, value): + self._sc = value + + def __iter__(self): + return iter(self._sc) + + def __aiter__(self): + return as_aiter(iter(self._sc)) + + class DocumentCollectionZipDownloadView(AuthMixin, PkSlugMixin, DetailView): model = DocumentCollection redirect_url_name = "filingcabinet:document-collection_zip" @@ -236,7 +257,7 @@ def render_to_response(self, context): arcname=ensure_unique_filename(filename_counter, filename), ) - resp = StreamingHttpResponse( + resp = ZipStreamResponse( archive_stream, content_type="application/zip", )