diff --git a/starlette/responses.py b/starlette/responses.py index fd156f84..c711dfa3 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -353,7 +353,7 @@ class FileResponse(Response): 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: @@ -438,11 +438,8 @@ class FileResponse(Response): } ) - @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]]: diff --git a/tests/test_responses.py b/tests/test_responses.py index 298bc3b0..f22b43b0 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -336,6 +336,22 @@ def test_file_response_with_method_warns(tmp_path: Path) -> None: 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)