http_range = headers.get("range")
http_if_range = headers.get("if-range")
- if http_range is None or (http_if_range is not None and not self._should_use_range(http_if_range, stat_result)):
+ if http_range is None or (http_if_range is not None and not self._should_use_range(http_if_range)):
await self._handle_simple(send, send_header_only)
else:
try:
}
)
- @classmethod
- def _should_use_range(cls, http_if_range: str, stat_result: os.stat_result) -> bool:
- etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
- etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'
- return http_if_range == formatdate(stat_result.st_mtime, usegmt=True) or http_if_range == etag
+ def _should_use_range(self, http_if_range: str) -> bool:
+ return http_if_range == self.headers["last-modified"] or http_if_range == self.headers["etag"]
@staticmethod
def _parse_range_header(http_range: str, file_size: int) -> list[tuple[int, int]]:
FileResponse(path=tmp_path, filename="example.png", method="GET")
+def test_file_response_with_range_header(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
+ content = b"file content"
+ filename = "hello.txt"
+ path = tmp_path / filename
+ path.write_bytes(content)
+ etag = '"a_non_autogenerated_etag"'
+ app = FileResponse(path=path, filename=filename, headers={"etag": etag})
+ client = test_client_factory(app)
+ response = client.get("/", headers={"range": "bytes=0-4", "if-range": etag})
+ assert response.status_code == status.HTTP_206_PARTIAL_CONTENT
+ assert response.content == content[:5]
+ assert response.headers["etag"] == etag
+ assert response.headers["content-length"] == "5"
+ assert response.headers["content-range"] == f"bytes 0-4/{len(content)}"
+
+
def test_set_cookie(test_client_factory: TestClientFactory, monkeypatch: pytest.MonkeyPatch) -> None:
# Mock time used as a reference for `Expires` by stdlib `SimpleCookie`.
mocked_now = dt.datetime(2037, 1, 22, 12, 0, 0, tzinfo=dt.timezone.utc)