Skip to content

Commit 3c8ab8e

Browse files
neolooongkarpetrosyanKludex
authored
Take weak ETags in consideration on StaticFiles (#2334)
Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com> Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
1 parent efa03eb commit 3c8ab8e

3 files changed

Lines changed: 7 additions & 2 deletions

File tree

starlette/responses.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ def set_stat_headers(self, stat_result: os.stat_result) -> None:
311311
content_length = str(stat_result.st_size)
312312
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
313313
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
314-
etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False)
314+
etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'
315315

316316
self.headers.setdefault("content-length", content_length)
317317
self.headers.setdefault("last-modified", last_modified)

starlette/staticfiles.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def is_not_modified(
225225
try:
226226
if_none_match = request_headers["if-none-match"]
227227
etag = response_headers["etag"]
228-
if if_none_match == etag:
228+
if etag in [tag.strip(" W/") for tag in if_none_match.split(",")]:
229229
return True
230230
except KeyError:
231231
pass

tests/test_staticfiles.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,11 @@ def test_staticfiles_304_with_etag_match(tmpdir, test_client_factory):
208208
second_resp = client.get("/example.txt", headers={"if-none-match": last_etag})
209209
assert second_resp.status_code == 304
210210
assert second_resp.content == b""
211+
second_resp = client.get(
212+
"/example.txt", headers={"if-none-match": f'W/{last_etag}, "123"'}
213+
)
214+
assert second_resp.status_code == 304
215+
assert second_resp.content == b""
211216

212217

213218
def test_staticfiles_304_with_last_modified_compare_last_req(

0 commit comments

Comments
 (0)