Skip to content

Commit

Permalink
remove old cache
Browse files Browse the repository at this point in the history
  • Loading branch information
peterdudfield committed Jan 22, 2024
1 parent 4aaf520 commit 8352f63
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@

CACHE_TIME_SECONDS = 120
cache_time_seconds = int(os.getenv("CACHE_TIME_SECONDS", CACHE_TIME_SECONDS))
DELETE_CACHE_TIME_SECONDS = 240
delete_cache_time_seconds = int(os.getenv("DELETE_CACHE_TIME_SECONDS", DELETE_CACHE_TIME_SECONDS))


def remove_old_cache(
last_updated: dict, response: dict, remove_cache_time_seconds: float = delete_cache_time_seconds
):
"""
Remove old cache entries from the cache
:param last_updated: dict of last updated times
:param response: dict of responses, same keys as last_updated
:param remove_cache_time_seconds: the amount of time, after which the cache should be removed
"""
now = datetime.now(tz=timezone.utc)
logger.info("Removing old cache entries")
keys_to_remove = []
for key, value in last_updated.items():
if now - timedelta(seconds=remove_cache_time_seconds) > value:
logger.debug(f"Removing {key} from cache, ({value})")
keys_to_remove.append(key)

for key in keys_to_remove:
last_updated.pop(key)
response.pop(key)

return last_updated, response


def cache_response(func):
Expand Down Expand Up @@ -47,11 +74,16 @@ def wrapper(*args, **kwargs): # noqa
request = route_variables.get("request", None)
save_api_call_to_db(session=session, user=user, request=request)

if 'background_tasks' in route_variables:
route_variables['background_tasks'].add_task(cache_response, last_updated)

# drop session and user
for var in ["session", "user", "request"]:
if var in route_variables:
route_variables.pop(var)

last_updated, response = remove_old_cache(last_updated, response)

# make route_variables into a string
route_variables = json.dumps(route_variables)

Expand Down

0 comments on commit 8352f63

Please sign in to comment.