From b24a5dc39ec5cdad94d6546b78b09bf31843f279 Mon Sep 17 00:00:00 2001 From: Jordan Cook Date: Fri, 30 Dec 2022 12:52:38 -0600 Subject: Add an example of keeping a history of previously cached response versions --- docs/examples.md | 17 +++++++++++++++++ examples/history.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 examples/history.py 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() -- cgit v1.2.1