From cd5261fae7c34014686d0a2b7af6078f45e64d2c Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 10 Jan 2024 14:56:51 -1000 Subject: [PATCH] Fix double compress when compression enabled and compressed file exists (#8014) (cherry picked from commit 92655a50987e8bdfb6241dabbedc4c3cc8f55272) --- CHANGES/8014.bugfix | 1 + aiohttp/web_fileresponse.py | 4 ++++ tests/test_web_sendfile_functional.py | 30 ++++++++++++++++++++++++++- 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 CHANGES/8014.bugfix diff --git a/CHANGES/8014.bugfix b/CHANGES/8014.bugfix new file mode 100644 index 00000000000..681bb5966ae --- /dev/null +++ b/CHANGES/8014.bugfix @@ -0,0 +1 @@ +Fix double compress when compression enabled and compressed file exists diff --git a/aiohttp/web_fileresponse.py b/aiohttp/web_fileresponse.py index c3b3814974e..6496ffaf317 100644 --- a/aiohttp/web_fileresponse.py +++ b/aiohttp/web_fileresponse.py @@ -267,6 +267,10 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter self.headers[hdrs.CONTENT_ENCODING] = encoding if gzip: self.headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING + # Disable compression if we are already sending + # a compressed file since we don't want to double + # compress. + self._compression = False self.etag = etag_value # type: ignore[assignment] self.last_modified = st.st_mtime # type: ignore[assignment] diff --git a/tests/test_web_sendfile_functional.py b/tests/test_web_sendfile_functional.py index 3f4f13354ec..31f22892f66 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -250,7 +250,35 @@ async def handler(request): await client.close() -async def test_static_file_with_content_encoding(aiohttp_client, sender) -> None: +async def test_static_file_with_gziped_counter_part_enable_compression( + aiohttp_client: Any, sender: Any +): + """Test that enable_compression does not double compress when a .gz file is also present.""" + filepath = pathlib.Path(__file__).parent / "hello.txt" + + async def handler(request): + resp = sender(filepath) + resp.enable_compression() + return resp + + app = web.Application() + app.router.add_get("/", handler) + client = await aiohttp_client(app) + + resp = await client.get("/") + assert resp.status == 200 + body = await resp.read() + assert body == b"hello aiohttp\n" + assert resp.headers["Content-Type"] == "text/plain" + assert resp.headers.get("Content-Encoding") == "gzip" + resp.close() + await resp.release() + await client.close() + + +async def test_static_file_with_content_encoding( + aiohttp_client: Any, sender: Any +) -> None: filepath = pathlib.Path(__file__).parent / "hello.txt.gz" async def handler(request):