Updated to have a cache that survives the restart of the application

Added ability to call the api to let the filecache refresh every night
This commit is contained in:
Computerboer
2023-10-22 14:24:05 +02:00
parent cf1f695971
commit 4f12de7b26
5 changed files with 48 additions and 10 deletions

View File

@@ -1,4 +1,10 @@
from datetime import datetime, timedelta
import os.path
from pathlib import Path
import time
import json
from models.location import JsonEncoder
cache = {}
@@ -29,6 +35,33 @@ class CacheObj:
self.time=datetime.now()
def isOlderThanHours(self, hours):
#print(f'checking time cacheobject {self.time} < {datetime.now() - timedelta(hours=hours)}')
print('checking time cacheobject ' + self.key + ': ' + str(self.time) + " < " + str(datetime.now() - timedelta(hours=hours)))
return self.time < datetime.now() - timedelta(hours=hours)
class FileCache():
def get(key, notOlderThanHours = 24):
filepath = "./filecache/" + key + ".json"
cachefile = Path(filepath)
if cachefile.is_file():
ti_m = os.path.getmtime(filepath)
#checks last modified age of file, and removes it if it is too old
print('checking time cachefile ' + filepath + ': ' + str(ti_m) + " < " + str(time.time() - (3600 * notOlderThanHours)))
if(ti_m < time.time() - (3600 * notOlderThanHours)):
print()
os.remove(filepath);
return None;
with open(filepath) as json_file:
json_data = json.load(json_file);
print('returning json data from cachefile: ' + key)
return json_data;
return None
def add(key, obj):
print(str(datetime.now()) + ' adding filecacheobject ' + key);
json_data = JsonEncoder().encode(obj)
with open("./filecache/" + key + ".json", 'w') as f:
f.write(json_data)