Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Expose HTTP cache storage timestamp via the cache_timestamp meta key (#8034)

Adrian6057f02ddeb7
diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rst
index 55945fd96..8caf2a39c 100644
--- a/docs/topics/downloader-middleware.rst
+++ b/docs/topics/downloader-middleware.rst
@@ -381,6 +381,15 @@ HttpCacheMiddleware
You can also avoid caching a response on every policy using :reqmeta:`dont_cache` meta key equals ``True``.
+ .. reqmeta:: cache_timestamp
+
+ .. versionadded:: VERSION
+
+ When a response comes from the cache, its :attr:`~scrapy.http.Response.meta`
+ exposes the :reqmeta:`cache_timestamp` key: the Unix timestamp of when the
+ response was stored, useful e.g. to interpret dates relative to the time
+ the page was downloaded rather than to the current time.
+
.. module:: scrapy.extensions.httpcache
:noindex:
@@ -542,6 +551,10 @@ class, including those of third-party plugins, are cached and restored intact.
:param request: the request to find cached response for
:type request: :class:`~scrapy.Request` object
+ On a cache hit, set ``request.meta["cache_timestamp"]`` (see
+ :reqmeta:`cache_timestamp`) to the Unix timestamp of when the response
+ was stored.
+
.. method:: store_response(spider, request, response)
Store the given response in the cache.
diff --git a/docs/topics/request-response.rst b/docs/topics/request-response.rst
index 0f4422d14..93dcc9ab4 100644
--- a/docs/topics/request-response.rst
+++ b/docs/topics/request-response.rst
@@ -831,6 +831,7 @@ Those are:
* :reqmeta:`allow_offsite`
* :reqmeta:`autothrottle_dont_adjust_delay`
* :reqmeta:`bindaddress`
+* :reqmeta:`cache_timestamp`
* :reqmeta:`cookiejar`
* :reqmeta:`depth`
* :reqmeta:`dont_cache`
diff --git a/scrapy/downloadermiddlewares/httpcache.py b/scrapy/downloadermiddlewares/httpcache.py
index 331543d83..bfc6e66ea 100644
--- a/scrapy/downloadermiddlewares/httpcache.py
+++ b/scrapy/downloadermiddlewares/httpcache.py
@@ -145,6 +145,7 @@ class HttpCacheMiddleware:
return cachedresponse
self.stats.inc_value("httpcache/invalidate")
+ request.meta.pop("cache_timestamp", None)
self._cache_response(response, request)
return response
diff --git a/scrapy/extensions/httpcache.py b/scrapy/extensions/httpcache.py
index f7b1c73d4..d8ef3e3cd 100644
--- a/scrapy/extensions/httpcache.py
+++ b/scrapy/extensions/httpcache.py
@@ -269,9 +269,11 @@ class DbmCacheStorage:
self.db.close()
def retrieve_response(self, spider: Spider, request: Request) -> Response | None:
- data = self._read_data(spider, request)
- if data is None:
+ result = self._read_data(spider, request)
+ if result is None:
return None # not cached
+ data, ts = result
+ request.meta["cache_timestamp"] = ts
return response_from_dict(data)
def store_response(
@@ -281,18 +283,21 @@ class DbmCacheStorage:
self.db[f"{key}_data"] = pickle.dumps(response.to_dict(), protocol=4)
self.db[f"{key}_time"] = str(time())
- def _read_data(self, spider: Spider, request: Request) -> dict[str, Any] | None:
+ def _read_data(
+ self, spider: Spider, request: Request
+ ) -> tuple[dict[str, Any], float] | None:
key = self._fingerprinter.fingerprint(request).hex()
db = self.db
tkey = f"{key}_time"
if tkey not in db:
return None # not found
- ts = db[tkey]
- if 0 < self.expiration_secs < time() - float(ts):
+ ts = float(db[tkey])
+ if 0 < self.expiration_secs < time() - ts:
return None # expired
- return cast("dict[str, Any]", pickle.loads(db[f"{key}_data"])) # noqa: S301
+ data = cast("dict[str, Any]", pickle.loads(db[f"{key}_data"])) # noqa: S301
+ return data, ts
class FilesystemCacheStorage:
@@ -339,6 +344,7 @@ class FilesystemCacheStorage:
if datapath.exists():
with self._open(datapath, "rb") as f:
data.update(pickle.load(f)) # noqa: S301
+ request.meta["cache_timestamp"] = metadata["timestamp"]
return response_from_dict(data)
def store_response(
diff --git a/scrapy/spidermiddlewares/metacopy.py b/scrapy/spidermiddlewares/metacopy.py
index 2bef974d6..a46e8209f 100644
--- a/scrapy/spidermiddlewares/metacopy.py
+++ b/scrapy/spidermiddlewares/metacopy.py
@@ -25,6 +25,7 @@ class MetaCopyDetectionMiddleware(BaseSpiderMiddleware):
"_auth_proxy",
"_dont_cache",
"_scheme_proxy",
+ "cache_timestamp",
"download_latency",
"redirect_reasons",
"redirect_times",
diff --git a/tests/test_downloadermiddleware_httpcache.py b/tests/test_downloadermiddleware_httpcache.py
index 6baf97896..5a02e6861 100644
--- a/tests/test_downloadermiddleware_httpcache.py
+++ b/tests/test_downloadermiddleware_httpcache.py
@@ -130,10 +130,13 @@ class StorageTestMixin(TestBase):
request2 = self.request.copy()
assert storage.retrieve_response(crawler.spider, request2) is None
+ before = time.time()
storage.store_response(crawler.spider, self.request, self.response)
+ after = time.time()
response2 = storage.retrieve_response(crawler.spider, request2)
assert isinstance(response2, HtmlResponse) # content-type header
self.assertEqualResponse(self.response, response2)
+ assert before <= request2.meta["cache_timestamp"] <= after
expired = time.time() + storage.expiration_secs + 1
with mock.patch("scrapy.extensions.httpcache.time", return_value=expired):
@@ -232,6 +235,22 @@ class StorageTestMixin(TestBase):
class PolicyTestMixin(TestBase):
"""Mixin containing policy-specific test methods."""
+ def test_cache_timestamp(self):
+ with self._middleware() as mw:
+ assert mw.process_request(self.request) is None
+ assert "cache_timestamp" not in self.request.meta
+
+ before = time.time()
+ mw.process_response(self.request, self.response)
+ after = time.time()
+
+ if not mw.policy.should_cache_response(self.response, self.request):
+ return
+
+ response = mw.process_request(self.request)
+ assert isinstance(response, Response)
+ assert before <= self.request.meta["cache_timestamp"] <= after
+
def test_dont_cache(self):
with self._middleware() as mw:
self.request.meta["dont_cache"] = True
@@ -704,6 +723,22 @@ class RFC2616PolicyTestMixin(PolicyTestMixin):
self.assertEqualResponse(res1, res2)
assert "cached" in res2.flags
+ def test_cache_timestamp_not_leaked_on_invalidate(self):
+ # A stale cached response invalidated by a fresh network response must
+ # not leave its storage timestamp behind on the request meta.
+ with self._middleware() as mw:
+ req0 = Request("http://example.com")
+ res0 = Response(req0.url, headers={"Expires": self.yesterday})
+ self._process_requestresponse(mw, req0, res0)
+
+ assert mw.process_request(req0) is None
+ assert "cache_timestamp" in req0.meta
+
+ res1 = res0.replace(body=b"new body")
+ response = mw.process_response(req0, res1)
+ assert response is res1
+ assert "cache_timestamp" not in req0.meta
+
def test_process_exception(self):
with self._middleware() as mw:
res0 = Response(self.request.url, headers={"Expires": self.yesterday})