Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Take weak ETags in consideration on StaticFiles #2334

Merged
merged 9 commits into from
Dec 16, 2023
2 changes: 1 addition & 1 deletion starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def set_stat_headers(self, stat_result: os.stat_result) -> None:
content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False)
etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'

self.headers.setdefault("content-length", content_length)
self.headers.setdefault("last-modified", last_modified)
Expand Down
2 changes: 1 addition & 1 deletion starlette/staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def is_not_modified(
try:
if_none_match = request_headers["if-none-match"]
etag = response_headers["etag"]
if if_none_match == etag:
if etag in [tag.strip(" W/") for tag in if_none_match.split(",")]:
return True
except KeyError:
pass
Expand Down
5 changes: 5 additions & 0 deletions tests/test_staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,11 @@ def test_staticfiles_304_with_etag_match(tmpdir, test_client_factory):
second_resp = client.get("/example.txt", headers={"if-none-match": last_etag})
assert second_resp.status_code == 304
assert second_resp.content == b""
second_resp = client.get(
"/example.txt", headers={"if-none-match": f'W/{last_etag}, "123"'}
)
assert second_resp.status_code == 304
assert second_resp.content == b""


def test_staticfiles_304_with_last_modified_compare_last_req(
Expand Down