summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJordan Cook <jordan.cook.git@proton.me>2022-12-30 12:52:38 -0600
committerJordan Cook <jordan.cook.git@proton.me>2023-03-01 17:36:53 -0600
commitb24a5dc39ec5cdad94d6546b78b09bf31843f279 (patch)
tree9bffb0304ef66b09c86d409e998fe46aeb17c295
parent812301ab85a3b54387dcebd7d65407ace2589b9f (diff)
downloadrequests-cache-history-example.tar.gz
Add an example of keeping a history of previously cached response versionshistory-example
-rw-r--r--docs/examples.md17
-rw-r--r--examples/history.py42
2 files changed, 59 insertions, 0 deletions
diff --git a/docs/examples.md b/docs/examples.md
index d193680..e9cb3ce 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -202,6 +202,23 @@ The following scripts can also be found in the
:::
+### Response history
+```{include} ../examples/history.py
+:start-line: 2
+:end-line: 3
+```
+
+:::{dropdown} Example
+:animate: fade-in-slide-down
+:color: primary
+:icon: file-code
+
+[benchmark.py](https://github.com/requests-cache/requests-cache/blob/main/examples/history.py)
+```{literalinclude} ../examples/history.py
+:lines: 5-
+```
+:::
+
### Using with GitHub Actions
This example shows how to use requests-cache with [GitHub Actions](https://docs.github.com/en/actions).
Key points:
diff --git a/examples/history.py b/examples/history.py
new file mode 100644
index 0000000..fb99e3d
--- /dev/null
+++ b/examples/history.py
@@ -0,0 +1,42 @@
+#!/usr/bin/env python3
+"""
+An example of keeping a history of cached responses, for later comparison or analysis
+"""
+from time import sleep
+
+from requests_cache import CachedSession
+
+
+class CachedHistorySession(CachedSession):
+ """A CachedSession that keeps a copy of all previously cached responses"""
+
+ def send(self, *args, **kwargs):
+ """Save a copy of every new response"""
+ response = super().send(*args, **kwargs)
+ if not response.from_cache:
+ self.cache.save_response(response, f'{response.cache_key}_{response.created_at}')
+ return response
+
+ def get_response_history(self, response):
+ """Get a history of previously cached versions of the given response"""
+ return [
+ self.cache.responses[k]
+ for k in self.cache.responses.keys()
+ if k.startswith(response.cache_key) and k != response.cache_key
+ ]
+
+
+def demo():
+ session = CachedHistorySession(expire_after=1)
+ n_history_items = 3
+ for i in range(n_history_items):
+ response = session.get('https://httpbin.org/get')
+ if i < n_history_items - 1:
+ sleep(1)
+
+ for r in session.get_response_history(response):
+ print(r)
+
+
+if __name__ == '__main__':
+ demo()