Skip to content

Commit

Permalink
Apply review suggestions and other renames
Browse files Browse the repository at this point in the history
Co-authored-by: Sviatoslav Sydorenko (Святослав Сидоренко) <[email protected]>
  • Loading branch information
steverep and webknjaz committed Jan 30, 2024
1 parent e7de51d commit 80caa3c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 21 deletions.
2 changes: 1 addition & 1 deletion CHANGES/8062.feature → CHANGES/8062.feature.rst
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Added server capability to check for static files with Brotli compression via a ``.br`` extension -- by :user:`steverep`

This comment has been minimized.

Copy link
@webknjaz

webknjaz Jan 30, 2024

Author Member

@Dreamsorcerer check out how GitHub picks up the correct lexer for highlighting once a changelog fragment has that .rst suffix ^

Added server capability to check for static files with Brotli compression via a ``.br`` extension -- by :user:`steverep`.
38 changes: 20 additions & 18 deletions aiohttp/web_fileresponse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import pathlib
import sys
from contextlib import suppress
from typing import (
IO,
TYPE_CHECKING,
Expand Down Expand Up @@ -131,32 +132,33 @@ async def _precondition_failed(
self.content_length = 0
return await super().prepare(request)

def _get_file_path_stat_and_gzip(
def _get_file_path_stat_encoding(
self, accept_encoding: str
) -> Tuple[pathlib.Path, os.stat_result, Optional[str]]:
"""Return the file path, stat result, and possible compression type.
"""Return the file path, stat result, and encoding.
If an uncompressed file is returned, the encoding is set to ``None``.
This method should be called from a thread executor
since it calls os.stat which may block.
"""
filepath = self._path
for extension, encoding in ENCODING_EXTENSIONS.items():
if encoding in accept_encoding:
compressed_path = filepath.with_name(filepath.name + extension)
try:
return compressed_path, compressed_path.stat(), encoding
except OSError:
# Try the next extension
pass
file_path = self._path
for file_extension, file_encoding in ENCODING_EXTENSIONS.items():
if file_encoding not in accept_encoding:
continue

compressed_path = file_path.with_suffix(file_path.suffix + file_extension)
with suppress(OSError):
return compressed_path, compressed_path.stat(), file_encoding

# Fallback to the uncompressed file
return filepath, filepath.stat(), None
return file_path, file_path.stat(), None

async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]:
loop = asyncio.get_event_loop()
accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "")
filepath, st, file_compression = await loop.run_in_executor(
None, self._get_file_path_stat_and_gzip, accept_encoding
file_path, st, file_encoding = await loop.run_in_executor(
None, self._get_file_path_stat_encoding, accept_encoding
)

etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}"
Expand Down Expand Up @@ -189,11 +191,11 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter

ct = None
if hdrs.CONTENT_TYPE not in self.headers:
ct, encoding = mimetypes.guess_type(str(filepath))
ct, encoding = mimetypes.guess_type(str(file_path))
if not ct:
ct = "application/octet-stream"
else:
encoding = file_compression
encoding = file_encoding

status = self._status
file_size = st.st_size
Expand Down Expand Up @@ -273,7 +275,7 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter
self.content_type = ct
if encoding:
self.headers[hdrs.CONTENT_ENCODING] = encoding
if file_compression:
if file_encoding:
self.headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING
# Disable compression if we are already sending
# a compressed file since we don't want to double
Expand All @@ -297,7 +299,7 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter
if count == 0 or must_be_empty_body(request.method, self.status):
return await super().prepare(request)

fobj = await loop.run_in_executor(None, filepath.open, "rb")
fobj = await loop.run_in_executor(None, file_path.open, "rb")
if start: # be aware that start could be None or int=0 here.
offset = start
else:
Expand Down
4 changes: 2 additions & 2 deletions tests/test_web_sendfile_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ async def handler(request):
async def test_static_file_custom_content_type_compress(
aiohttp_client: Any, sender: Any, accept_encoding: str, expect_encoding: str
):
"""Test static compressed files are returned with expected content type and encoding"""
"""Test static compressed files are returned with expected content type and encoding."""
filepath = pathlib.Path(__file__).parent / "hello.txt"

async def handler(request):
Expand Down Expand Up @@ -297,7 +297,7 @@ async def handler(request):
async def test_static_file_with_content_encoding(
aiohttp_client: Any, sender: Any, extension: str, expect_encoding: str
) -> None:
"""Test requesting of static compressed files returns correct content type and encoding"""
"""Test requesting of static compressed files returns correct content type and encoding."""
filepath = pathlib.Path(__file__).parent / ("hello.txt" + extension)

async def handler(request):
Expand Down

0 comments on commit 80caa3c

Please sign in to comment.