summaryrefslogtreecommitdiff
path: root/django/middleware/gzip.py
diff options
context:
space:
mode:
authorCarlton Gibson <carlton.gibson@noumenal.es>2022-12-13 16:15:25 +0100
committerCarlton Gibson <carlton.gibson@noumenal.es>2022-12-22 10:41:12 +0100
commit0bd2c0c9015b53c41394a1c0989afbfd94dc2830 (patch)
tree6b24758335cf10eeedfdf7dec50cda3500796305 /django/middleware/gzip.py
parentae0899be0d787fbfc5f5ab2b18c5a8219d822d2b (diff)
Fixed #33735 -- Added async support to StreamingHttpResponse.
Thanks to Florian Vazelle for initial exploratory work, and to Nick Pope and Mariusz Felisiak for review.
Diffstat (limited to 'django/middleware/gzip.py')
-rw-r--r--django/middleware/gzip.py22
1 files changed, 18 insertions, 4 deletions
diff --git a/django/middleware/gzip.py b/django/middleware/gzip.py
index d91246c007..45be6ccb43 100644
--- a/django/middleware/gzip.py
+++ b/django/middleware/gzip.py
@@ -31,12 +31,26 @@ class GZipMiddleware(MiddlewareMixin):
return response
if response.streaming:
+ if response.is_async:
+ # pull to lexical scope to capture fixed reference in case
+ # streaming_content is set again later.
+ orignal_iterator = response.streaming_content
+
+ async def gzip_wrapper():
+ async for chunk in orignal_iterator:
+ yield compress_string(
+ chunk,
+ max_random_bytes=self.max_random_bytes,
+ )
+
+ response.streaming_content = gzip_wrapper()
+ else:
+ response.streaming_content = compress_sequence(
+ response.streaming_content,
+ max_random_bytes=self.max_random_bytes,
+ )
# Delete the `Content-Length` header for streaming content, because
# we won't know the compressed size until we stream it.
- response.streaming_content = compress_sequence(
- response.streaming_content,
- max_random_bytes=self.max_random_bytes,
- )
del response.headers["Content-Length"]
else:
# Return the compressed content only if it's actually shorter.