Download src/shared/query_cache.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 4.24 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/query_cache.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/shared/query_cache.py
-
curl -L -o query_cache.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/query_cache.py
4.24 kB
| """ | |
| Query result caching for frequently accessed data | |
| In-memory cache with LRU eviction until Redis is available | |
| """ | |
| import hashlib | |
| import json | |
| from datetime import UTC, datetime, timedelta, timezone | |
| from functools import lru_cache, wraps | |
| from typing import Any, Callable, Optional | |
| import structlog | |
| logger = structlog.get_logger(__name__) | |
| class QueryCache: | |
| """ | |
| Simple in-memory query cache with TTL support | |
| Uses LRU cache for efficient memory management | |
| """ | |
| _cache = {} # type: ignore[name-defined, index, return-value, var-annotated] | |
| _timestamps = {} # type: ignore[name-defined, index, return-value, var-annotated] | |
| def get(cls, key: str, ttl: timedelta) -> Any | None: | |
| """Get cached value if not expired""" | |
| if key not in cls._cache: | |
| return None | |
| timestamp = cls._timestamps.get(key) | |
| if timestamp and datetime.now(UTC) - timestamp > ttl: | |
| # Expired - remove from cache | |
| cls._cache.pop(key, None) | |
| cls._timestamps.pop(key, None) | |
| return None | |
| return cls._cache[key] | |
| def set(cls, key: str, value: Any): | |
| """Set cached value with current timestamp""" | |
| cls._cache[key] = value | |
| cls._timestamps[key] = datetime.now(UTC) | |
| def invalidate(cls, key: str): | |
| """Remove specific key from cache""" | |
| cls._cache.pop(key, None) | |
| cls._timestamps.pop(key, None) | |
| def invalidate_pattern(cls, pattern: str): | |
| """Remove all keys matching pattern""" | |
| keys_to_remove = [k for k in cls._cache.keys() if pattern in k] | |
| for key in keys_to_remove: | |
| cls._cache.pop(key, None) | |
| cls._timestamps.pop(key, None) | |
| def clear(cls): | |
| """Clear entire cache""" | |
| cls._cache.clear() | |
| cls._timestamps.clear() | |
| def stats(cls) -> dict: | |
| """Get cache statistics""" | |
| return { | |
| "size": len(cls._cache), | |
| "keys": list(cls._cache.keys())[:10], # First 10 keys for monitoring | |
| } | |
| def cache_query_result(ttl: timedelta, key_prefix: str = ""): | |
| """ | |
| Decorator for caching query results | |
| Usage: | |
| @cache_query_result(ttl=timedelta(minutes=5), key_prefix="inventory") | |
| def get_inventory_item(self, item_id): | |
| return self.db.query(Inventory).filter(...).first() | |
| """ | |
| def decorator(func: Callable) -> Callable: | |
| def wrapper(*args, **kwargs): | |
| # Generate cache key from function name and arguments | |
| key_parts = [key_prefix, func.__name__] | |
| # Add args (skip self) | |
| for arg in args[1:]: # Skip self | |
| key_parts.append(str(arg)) | |
| # Add kwargs | |
| for k, v in sorted(kwargs.items()): | |
| key_parts.append(f"{k}={v}") | |
| cache_key = ":".join(key_parts) | |
| # Try to get from cache | |
| cached_value = QueryCache.get(cache_key, ttl) | |
| if cached_value is not None: | |
| logger.debug(f"Cache hit: {cache_key}") | |
| return cached_value | |
| # Execute query | |
| result = func(*args, **kwargs) | |
| # Cache result | |
| if result is not None: | |
| QueryCache.set(cache_key, result) | |
| logger.debug(f"Cache set: {cache_key}") | |
| return result | |
| return wrapper | |
| return decorator | |
| def cached_lookup(model_name: str, lookup_key: str, lookup_value: str) -> str | None: | |
| """ | |
| LRU cached lookup for reference data | |
| Returns ID as string for simple lookups | |
| """ | |
| # This is a placeholder - actual implementation would query DB | |
| # Used for frequently accessed reference data like warehouses, vendors, etc. | |
| return None | |
| def invalidate_model_cache(model_name: str): | |
| """Invalidate all cache entries for a model""" | |
| QueryCache.invalidate_pattern(model_name.lower()) | |
| logger.info(f"Invalidated cache for model: {model_name}") | |
| # Export utilities | |
| __all__ = [ | |
| "QueryCache", | |
| "cache_query_result", | |
| "cached_lookup", | |
| "invalidate_model_cache", | |
| ] | |