Add cache data

This commit is contained in:
Antonio J. Delgado 2025-02-24 21:20:48 +02:00
parent 8dd844888f
commit ad8a4ed906

View file

@ -7,13 +7,25 @@
import sys
import os
import json
import time
import logging
from logging.handlers import SysLogHandler
import click
import click_config_file
HOME_FOLDER = os.environ.get('HOME', os.environ.get('USERPROFILE', '/'))
if HOME_FOLDER == '/':
CACHE_FOLDER = '/var/cache'
LOG_FOLDER = '/var/log/'
else:
CACHE_FOLDER = f"{HOME_FOLDER}/.local/"
LOG_FOLDER = f"{HOME_FOLDER}/log/"
class __project_codename_camel__:
"""__description__"""
def __init__(self, **kwargs):
self.config = kwargs
@ -30,6 +42,35 @@ class __project_codename_camel__:
'__project_codename__.log'
)
self._init_log()
self._default_data = {
"last_update": 0,
}
self.data = self._read_cached_data()
def close(self):
'''Close class and save data'''
self._save_cached_data(self.data)
def _read_cached_data(self):
if os.path.exists(self.config['cache_file']):
with open(self.config['cache_file'], 'r', encoding='utf-8') as cache_file:
try:
cached_data = json.load(cache_file)
if (
'last_update' in cached_data and
cached_data['last_update'] + self.config['max_cache_age'] > time.time()
):
cached_data = self._default_data
except json.decoder.JSONDecodeError:
cached_data = self._default_data
return cached_data
else:
return self._default_data
def _save_cached_data(self, data):
data['last_update'] = time.time()
with open(self.config['cache_file'], 'w', encoding='utf-8') as cache_file:
json.dump(data, cache_file, indent=2)
def _init_log(self):
''' Initialize log object '''
@ -82,12 +123,24 @@ class __project_codename_camel__:
),
help='Set the debug level for the standard output.'
)
@click.option('--log-file', '-l', help="File to store all debug messages.")
@click.option(
'--log-file',
'-l',
default=f"{LOG_FOLDER}/__project_code_name__.log",
help="File to store all debug messages."
)
@click.option(
'--max-cache-age',
'-a',
default=60*60*24*7,
help='Max age in seconds for the cache'
)
# @click.option("--dummy","-n", is_flag=True,
# help="Don't do anything, just show what would be done.")
@click_config_file.configuration_option()
def __main__(**kwargs):
return __project_codename_camel__(**kwargs)
obj = __project_codename_camel__(**kwargs)
obj.close()
if __name__ == "__main__":
__main__()