generated from python-discord/code-jam-template
-
Notifications
You must be signed in to change notification settings - Fork 11
/
cache.py
39 lines (29 loc) · 1.06 KB
/
cache.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
"""Tools for caching requests to external APIs.
Caching is used to reduce the number of requests to external APIs.
"""
from requests_cache import CachedSession
from requests_cache.backends import FileCache
from wtpython.settings import REQUEST_CACHE_DURATION, REQUEST_CACHE_LOCATION
class CachedResponse:
"""Class for caching web queries.
This class should be extended by any class that makes web queries.
The `cache_key` should be defined to avoid caching conflicts.
"""
cache_key = 'wtpython'
def __init__(self, clear_cache: bool = False) -> None:
"""Initialize the session and cache.
Args:
clear_cache: If True, clear the cache.
Returns:
None
"""
self.session = CachedSession(
self.cache_key,
backend=FileCache(REQUEST_CACHE_LOCATION),
expire_after=REQUEST_CACHE_DURATION,
)
if clear_cache:
self.session.cache.clear()
def __del__(self) -> None:
"""Close the session on exit."""
self.session.close()