-
Notifications
You must be signed in to change notification settings - Fork 137
/
core.py
300 lines (241 loc) · 10.4 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
requests_cache.core
~~~~~~~~~~~~~~~~~~~
Core functions for configuring cache and monkey patching ``requests``
"""
from contextlib import contextmanager
from datetime import datetime, timedelta
from operator import itemgetter
import requests
from requests import Session as OriginalSession
from requests.hooks import dispatch_hook
from requests_cache import backends
from requests_cache.compat import basestring
try:
ver = tuple(map(int, requests.__version__.split(".")))
except ValueError:
pass
else:
# We don't need to dispatch hook in Requests <= 1.1.0
if ver < (1, 2, 0):
dispatch_hook = lambda key, hooks, hook_data, *a, **kw: hook_data
del ver
class CachedSession(OriginalSession):
""" Requests ``Sessions`` with caching support.
"""
def __init__(self, cache_name='cache', backend=None, expire_after=None,
allowable_codes=(200,), allowable_methods=('GET',),
filter_fn=lambda r: True, old_data_on_error=False,
**backend_options):
"""
:param cache_name: for ``sqlite`` backend: cache file will start with this prefix,
e.g ``cache.sqlite``
for ``mongodb``: it's used as database name
for ``redis``: it's used as the namespace. This means all keys
are prefixed with ``'cache_name:'``
:param backend: cache backend name e.g ``'sqlite'``, ``'mongodb'``, ``'redis'``, ``'memory'``.
(see :ref:`persistence`). Or instance of backend implementation.
Default value is ``None``, which means use ``'sqlite'`` if available,
otherwise fallback to ``'memory'``.
:param expire_after: ``timedelta`` or number of seconds after cache will be expired
or `None` (default) to ignore expiration
:type expire_after: float
:param allowable_codes: limit caching only for response with this codes (default: 200)
:type allowable_codes: tuple
:param allowable_methods: cache only requests of this methods (default: 'GET')
:type allowable_methods: tuple
:param filter_fn: function to apply to each response; the response is only cached if
this returns `True`. Note that this function does not not modify
the cached response in any way.
:type filter_fn: function
:kwarg backend_options: options for chosen backend. See corresponding
:ref:`sqlite <backends_sqlite>`, :ref:`mongo <backends_mongo>`
and :ref:`redis <backends_redis>` backends API documentation
:param include_get_headers: If `True` headers will be part of cache key.
E.g. after get('some_link', headers={'Accept':'application/json'})
get('some_link', headers={'Accept':'application/xml'}) is not from cache.
:param ignored_parameters: List of parameters to be excluded from the cache key.
Useful when requesting the same resource through different
credentials or access tokens, passed as parameters.
:param old_data_on_error: If `True` it will return expired cached response if update fails
"""
self.cache = backends.create_backend(backend, cache_name, backend_options)
self._cache_name = cache_name
if expire_after is not None and not isinstance(expire_after, timedelta):
expire_after = timedelta(seconds=expire_after)
self._cache_expire_after = expire_after
self._cache_allowable_codes = allowable_codes
self._cache_allowable_methods = allowable_methods
self._filter_fn = filter_fn
self._return_old_data_on_error = old_data_on_error
self._is_cache_disabled = False
super(CachedSession, self).__init__()
def send(self, request, **kwargs):
if (self._is_cache_disabled
or request.method not in self._cache_allowable_methods):
response = super(CachedSession, self).send(request, **kwargs)
response.from_cache = False
return response
cache_key = self.cache.create_key(request)
def send_request_and_cache_response():
response = super(CachedSession, self).send(request, **kwargs)
if response.status_code in self._cache_allowable_codes:
self.cache.save_response(cache_key, response)
response.from_cache = False
return response
try:
response, timestamp = self.cache.get_response_and_time(cache_key)
except (ImportError, TypeError):
return send_request_and_cache_response()
if response is None:
return send_request_and_cache_response()
if self._cache_expire_after is not None:
is_expired = datetime.utcnow() - timestamp > self._cache_expire_after
if is_expired:
if not self._return_old_data_on_error:
self.cache.delete(cache_key)
return send_request_and_cache_response()
try:
new_response = send_request_and_cache_response()
except Exception:
return response
else:
if new_response.status_code not in self._cache_allowable_codes:
return response
return new_response
# dispatch hook here, because we've removed it before pickling
response.from_cache = True
response = dispatch_hook('response', request.hooks, response, **kwargs)
return response
def request(self, method, url, params=None, data=None, **kwargs):
response = super(CachedSession, self).request(
method, url,
_normalize_parameters(params),
_normalize_parameters(data),
**kwargs
)
if self._is_cache_disabled:
return response
main_key = self.cache.create_key(response.request)
# If self._return_old_data_on_error is set,
# responses won't always have the from_cache attribute.
if (hasattr(response, "from_cache") and not response.from_cache
and self._filter_fn(response) is not True):
self.cache.delete(main_key)
return response
for r in response.history:
self.cache.add_key_mapping(
self.cache.create_key(r.request), main_key
)
return response
@contextmanager
def cache_disabled(self):
"""
Context manager for temporary disabling cache
::
>>> s = CachedSession()
>>> with s.cache_disabled():
... s.get('http://httpbin.org/ip')
"""
self._is_cache_disabled = True
try:
yield
finally:
self._is_cache_disabled = False
def remove_expired_responses(self):
""" Removes expired responses from storage
"""
if not self._cache_expire_after:
return
self.cache.remove_old_entries(datetime.utcnow() - self._cache_expire_after)
def __repr__(self):
return (
"<CachedSession(%s('%s', ...), expire_after=%s, "
"allowable_methods=%s)>" % (
self.cache.__class__.__name__, self._cache_name,
self._cache_expire_after, self._cache_allowable_methods
)
)
def install_cache(cache_name='cache', backend=None, expire_after=None,
allowable_codes=(200,), allowable_methods=('GET',),
filter_fn=lambda r: True, session_factory=CachedSession,
**backend_options):
"""
Installs cache for all ``Requests`` requests by monkey-patching ``Session``
Parameters are the same as in :class:`CachedSession`. Additional parameters:
:param session_factory: Session factory. It must be class which inherits :class:`CachedSession` (default)
"""
if backend:
backend = backends.create_backend(backend, cache_name, backend_options)
class _ConfiguredCachedSession(session_factory):
def __init__(self):
super(_ConfiguredCachedSession, self).__init__(
cache_name=cache_name,
backend=backend,
expire_after=expire_after,
allowable_codes=allowable_codes,
allowable_methods=allowable_methods,
filter_fn=filter_fn,
**backend_options
)
_patch_session_factory(_ConfiguredCachedSession)
# backward compatibility
configure = install_cache
def uninstall_cache():
""" Restores ``requests.Session`` and disables cache
"""
_patch_session_factory(OriginalSession)
@contextmanager
def disabled():
"""
Context manager for temporary disabling globally installed cache
.. warning:: not thread-safe
::
>>> with requests_cache.disabled():
... requests.get('http://httpbin.org/ip')
... requests.get('http://httpbin.org/get')
"""
previous = requests.Session
uninstall_cache()
try:
yield
finally:
_patch_session_factory(previous)
@contextmanager
def enabled(*args, **kwargs):
"""
Context manager for temporary installing global cache.
Accepts same arguments as :func:`install_cache`
.. warning:: not thread-safe
::
>>> with requests_cache.enabled('cache_db'):
... requests.get('http://httpbin.org/get')
"""
install_cache(*args, **kwargs)
try:
yield
finally:
uninstall_cache()
def get_cache():
""" Returns internal cache object from globally installed ``CachedSession``
"""
return requests.Session().cache
def clear():
""" Clears globally installed cache
"""
get_cache().clear()
def remove_expired_responses():
""" Removes expired responses from storage
"""
return requests.Session().remove_expired_responses()
def _patch_session_factory(session_factory=CachedSession):
requests.Session = requests.sessions.Session = session_factory
def _normalize_parameters(params):
""" If builtin dict is passed as parameter, returns sorted list
of key-value pairs
"""
if type(params) is dict:
return sorted(params.items(), key=itemgetter(0))
return params