-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.py
81 lines (67 loc) · 2.34 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
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
import json
import datetime
from threading import Lock
import exceptions
class Cache:
def __init__(self, file_name):
self._file_name = file_name
self._content = {}
self._lock = Lock()
def __str__(self):
return self._content
def _load_json(self):
"""
loads data from json file to instance
"""
try:
with open(f"{self._file_name}.json", "r") as fh:
self._lock.acquire()
self._content = json.load(fh)
self._lock.release()
except:
exceptions.NoFile()
def put(self, url, new_information):
"""
recieves information about url, and adds to JSON
:param url: str
:param new_information: dictionary with last analysis date, last analysis results
"""
self._load_json()
self._content[url] = new_information
try:
with open(f"{self._file_name}.json", "w") as fh:
self._lock.acquire()
json.dump(self._content, fh)
self._lock.release()
except:
exceptions.FailedToSave()
def get_info(self, url: str, maxage: int):
"""gets information about url from cache file, if the data is still valid
:param url:str
:param maxage: maximum acceptable data entry age, in days (default = 180)
:return dict
"""
self._load_json()
# check if information in cache
if url not in self._content:
return None
# check if information still valid
today = datetime.datetime.now(tz=datetime.timezone.utc)
analysis_day = datetime.datetime.fromtimestamp(self._content[url]["Last analysis date"],
tz=datetime.timezone.utc)
delta = int((today - analysis_day).days)
if delta >= maxage:
self._lock.acquire()
del self._content[url]
try:
with open(f"{self._file_name}.json", "w") as fh:
json.dump(self._content, fh)
self._lock.release()
return None
except:
exceptions.FailedToSave()
# give information
return self._content[url]
def display_cache(self):
self._load_json()
return self._content