Skip to content

Commit de0318a

Browse files
committed
implemented async-only gzip middleware
1 parent 05461dc commit de0318a

File tree

1 file changed

+76
-0
lines changed
  • django_async_extensions/amiddleware

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
from django.utils.cache import patch_vary_headers
2+
from django.utils.regex_helper import _lazy_re_compile
3+
from django.utils.text import compress_sequence, compress_string
4+
5+
from django_async_extensions.amiddleware.base import AsyncMiddlewareMixin
6+
7+
8+
re_accepts_gzip = _lazy_re_compile(r"\bgzip\b")
9+
10+
11+
class AsyncGZipMiddleware(AsyncMiddlewareMixin):
12+
"""
13+
Compress content if the browser allows gzip compression.
14+
Set the Vary header accordingly, so that caches will base their storage
15+
on the Accept-Encoding header.
16+
"""
17+
18+
max_random_bytes = 100
19+
20+
async def process_response(self, request, response):
21+
# It's not worth attempting to compress really short responses.
22+
if not response.streaming and len(response.content) < 200:
23+
return response
24+
25+
# Avoid gzipping if we've already got a content-encoding.
26+
if response.has_header("Content-Encoding"):
27+
return response
28+
29+
patch_vary_headers(response, ("Accept-Encoding",))
30+
31+
ae = request.headers.get("accept-encoding", "")
32+
if not re_accepts_gzip.search(ae):
33+
return response
34+
35+
if response.streaming:
36+
if response.is_async:
37+
# pull to lexical scope to capture fixed reference in case
38+
# streaming_content is set again later.
39+
orignal_iterator = response.streaming_content
40+
41+
async def gzip_wrapper():
42+
async for chunk in orignal_iterator:
43+
yield compress_string(
44+
chunk,
45+
max_random_bytes=self.max_random_bytes,
46+
)
47+
48+
response.streaming_content = gzip_wrapper()
49+
else:
50+
response.streaming_content = compress_sequence(
51+
response.streaming_content,
52+
max_random_bytes=self.max_random_bytes,
53+
)
54+
# Delete the `Content-Length` header for streaming content, because
55+
# we won't know the compressed size until we stream it.
56+
del response.headers["Content-Length"]
57+
else:
58+
# Return the compressed content only if it's actually shorter.
59+
compressed_content = compress_string(
60+
response.content,
61+
max_random_bytes=self.max_random_bytes,
62+
)
63+
if len(compressed_content) >= len(response.content):
64+
return response
65+
response.content = compressed_content
66+
response.headers["Content-Length"] = str(len(response.content))
67+
68+
# If there is a strong ETag, make it weak to fulfill the requirements
69+
# of RFC 9110 Section 8.8.1 while also allowing conditional request
70+
# matches on ETags.
71+
etag = response.get("ETag")
72+
if etag and etag.startswith('"'):
73+
response.headers["ETag"] = "W/" + etag
74+
response.headers["Content-Encoding"] = "gzip"
75+
76+
return response

0 commit comments

Comments
 (0)