summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorJordan Cook <jordan.cook@pioneer.com>2022-02-15 13:16:07 -0600
committerJordan Cook <jordan.cook@pioneer.com>2022-02-15 14:05:26 -0600
commit49c1178ec30eefce10218811d7b3ed561d63f979 (patch)
treecdb0eaa916e2324ba3ac17c6cdf71e991c63a194 /examples
parentc2baccd8da967cadd4bf18e23e232e9ddcf267a9 (diff)
downloadrequests-cache-49c1178ec30eefce10218811d7b3ed561d63f979.tar.gz
Add documentation example for backtesting with time-machine
Diffstat (limited to 'examples')
-rw-r--r--examples/time_machine_backtesting.py39
1 files changed, 39 insertions, 0 deletions
diff --git a/examples/time_machine_backtesting.py b/examples/time_machine_backtesting.py
new file mode 100644
index 0000000..4ec9c42
--- /dev/null
+++ b/examples/time_machine_backtesting.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""
+An example of using the [time-machine](https://github.com/adamchainz/time-machine) library for backtesting,
+e.g., testing with cached responses that were available at an arbitrary time in the past.
+"""
+from datetime import datetime
+
+import requests
+import time_machine
+
+from requests_cache import CachedSession, set_response_defaults
+
+
+class BacktestCachedSession(CachedSession):
+ def request(self, method: str, url: str, **kwargs):
+ response = super().request(method, url, **kwargs)
+
+ # Response was cached after the (simulated) current time, so ignore it and send a new request
+ if response.created_at and response.created_at > datetime.utcnow():
+ new_response = requests.request(method, url, **kwargs)
+ return set_response_defaults(new_response)
+ else:
+ return response
+
+
+def demo():
+ session = BacktestCachedSession()
+ response = session.get('https://httpbin.org/get')
+ response = session.get('https://httpbin.org/get')
+ assert response.from_cache is True
+
+ # Response was not cached yet at this point, so we should get a fresh one
+ with time_machine.travel(datetime(2020, 1, 1)):
+ response = session.get('https://httpbin.org/get')
+ assert response.from_cache is False
+
+
+if __name__ == '__main__':
+ demo()