Skip to content

Commit 4e267a8

Browse files
authored
fix: Don't use the cache if the request has a Range header (#328)
fixes #327
1 parent 7e3edbf commit 4e267a8

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

cachecontrol/controller.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,11 @@ def _load_from_cache(self, request: PreparedRequest) -> HTTPResponse | None:
142142
"""
143143
Load a cached response, or return None if it's not available.
144144
"""
145+
# We do not support caching of partial content: so if the request contains a
146+
# Range header then we don't want to load anything from the cache.
147+
if "Range" in request.headers:
148+
return None
149+
145150
cache_url = request.url
146151
assert cache_url is not None
147152
cache_data = self.cache.get(cache_url)

tests/test_etag.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,31 @@ def test_etags_get_example(self, sess, server):
7979
# Make sure we updated our cache with the new etag'd response.
8080
assert self.cache.get(self.etag_url) == resp.raw
8181

82+
def test_etags_get_no_cache(self, sess, server):
83+
"""A 'Cache-Control: no-cache' header stops us from using the cache directly,
84+
but not from using the 'If-None-Match' header on the request."""
85+
# get our response
86+
r = sess.get(self.etag_url)
87+
assert "if-none-match" not in r.request.headers
88+
89+
r = sess.get(self.etag_url, headers={"Cache-Control": "no-cache"})
90+
assert "if-none-match" in r.request.headers
91+
assert r.status_code == 200
92+
93+
# This response does come from the cache, but only after the 304 response from
94+
# the server told us that was fine.
95+
assert r.from_cache
96+
97+
def test_etags_get_with_range(self, sess, server):
98+
"""A 'Range' header stops us from using the cache altogether."""
99+
# get our response
100+
r = sess.get(self.etag_url)
101+
102+
r = sess.get(self.etag_url, headers={"Range": "0-10"})
103+
assert "if-none-match" not in r.request.headers
104+
assert r.status_code == 200
105+
assert not r.from_cache
106+
82107

83108
class TestDisabledETags:
84109
"""Test our use of ETags when the response is stale and the

0 commit comments

Comments
 (0)