- Improvements to EntitlementsDomain & Services - Prechecks in Document domain - Add audit information to LicenseUsage
55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
from datetime import datetime, timedelta
|
|
from typing import Any, Dict, Optional
|
|
|
|
from flask import Flask
|
|
|
|
|
|
class CacheManager:
|
|
"""Manages general purpose caching for the application."""
|
|
|
|
def __init__(self):
|
|
"""Initialize the cache manager."""
|
|
self.cache = {}
|
|
|
|
def init_app(self, app: Flask) -> None:
|
|
pass
|
|
|
|
def get(self, key: str) -> Optional[Any]:
|
|
"""Get a value from cache if it exists and is not expired."""
|
|
if key not in self.cache:
|
|
return None
|
|
|
|
entry = self.cache[key]
|
|
if datetime.utcnow() > entry['expires_at']:
|
|
self.delete(key)
|
|
return None
|
|
|
|
return entry['value']
|
|
|
|
def set(self, key: str, value: Any, ttl: int = 3600) -> None:
|
|
"""Set a value in cache with a TTL in seconds."""
|
|
expires_at = datetime.utcnow() + timedelta(seconds=ttl)
|
|
self.cache[key] = {
|
|
'value': value,
|
|
'expires_at': expires_at
|
|
}
|
|
|
|
def delete(self, key: str) -> None:
|
|
"""Delete a value from cache."""
|
|
if key in self.cache:
|
|
del self.cache[key]
|
|
|
|
def clear(self) -> None:
|
|
"""Clear all cached values."""
|
|
self.cache = {}
|
|
|
|
def cleanup(self) -> None:
|
|
"""Remove all expired cache entries."""
|
|
now = datetime.utcnow()
|
|
expired_keys = [
|
|
key for key, entry in self.cache.items()
|
|
if now > entry['expires_at']
|
|
]
|
|
for key in expired_keys:
|
|
del self.cache[key]
|