Download cache.py from ineeds/now: direct link, hf CLI and curl.
- Browser
- Download file 4.14 kB
-
https://huggingface.co/spaces/ineeds/now/resolve/main/cache.py
- Command line
-
hf download hf://spaces/ineeds/now/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/ineeds/now/resolve/main/cache.py
4.14 kB
| """ | |
| Redis caching module with graceful fallback to in-memory dict when Redis is unavailable. | |
| Usage: | |
| from cache import cache_get, cache_set, cache_delete, cache_clear | |
| cache_set("products:list", products, ttl=300) | |
| products = cache_get("products:list") | |
| """ | |
| import os | |
| import json | |
| import time | |
| import logging | |
| from typing import Any, Optional | |
| log = logging.getLogger(__name__) | |
| REDIS_URL = os.environ.get("REDIS_URL", "") | |
| _redis_client = None | |
| _memory_cache: dict[str, tuple[Any, float]] = {} | |
| def _get_redis(): | |
| """Lazy-initialize Redis client. Returns None if unavailable.""" | |
| global _redis_client | |
| if _redis_client is not None: | |
| return _redis_client | |
| if not REDIS_URL: | |
| log.debug("No REDIS_URL — using in-memory cache") | |
| return None | |
| try: | |
| import redis | |
| _redis_client = redis.from_url(REDIS_URL, decode_responses=True, socket_timeout=2) | |
| _redis_client.ping() | |
| log.info("Redis connected (%s)", REDIS_URL.split("@")[-1] if "@" in REDIS_URL else REDIS_URL) | |
| return _redis_client | |
| except ImportError: | |
| log.warning("redis-py not installed — using in-memory cache") | |
| return None | |
| except Exception as e: | |
| log.warning("Redis unavailable: %s — using in-memory cache", e) | |
| _redis_client = None | |
| return None | |
| def cache_get(key: str) -> Optional[Any]: | |
| """Get value from cache. Returns None if not found.""" | |
| # Try Redis first | |
| r = _get_redis() | |
| if r is not None: | |
| try: | |
| val = r.get(key) | |
| if val is not None: | |
| return json.loads(val) | |
| return None | |
| except Exception: | |
| pass | |
| # Fallback to in-memory cache | |
| entry = _memory_cache.get(key) | |
| if entry is None: | |
| return None | |
| value, expires = entry | |
| if expires and time.time() > expires: | |
| del _memory_cache[key] | |
| return None | |
| return value | |
| def cache_set(key: str, value: Any, ttl: int = 300) -> None: | |
| """Set value in cache with TTL in seconds (default 5 min).""" | |
| serialized = json.dumps(value, default=str) | |
| # Try Redis | |
| r = _get_redis() | |
| if r is not None: | |
| try: | |
| r.setex(key, ttl, serialized) | |
| return | |
| except Exception: | |
| pass | |
| # Fallback to in-memory cache | |
| expires = time.time() + ttl if ttl > 0 else 0 | |
| _memory_cache[key] = (value, expires) | |
| def cache_delete(*keys: str) -> None: | |
| """Delete keys from cache.""" | |
| r = _get_redis() | |
| if r is not None: | |
| try: | |
| r.delete(*keys) | |
| except Exception: | |
| pass | |
| for k in keys: | |
| _memory_cache.pop(k, None) | |
| def cache_clear(pattern: str = "*") -> None: | |
| """Clear cache entries matching pattern.""" | |
| r = _get_redis() | |
| if r is not None: | |
| try: | |
| cursor = 0 | |
| while True: | |
| cursor, keys = r.scan(cursor, match=pattern, count=100) | |
| if keys: | |
| r.delete(*keys) | |
| if cursor == 0: | |
| break | |
| except Exception: | |
| pass | |
| if pattern == "*": | |
| _memory_cache.clear() | |
| else: | |
| import fnmatch | |
| to_delete = [k for k in _memory_cache if fnmatch.fnmatch(k, pattern)] | |
| for k in to_delete: | |
| del _memory_cache[k] | |
| def cache_stats() -> dict: | |
| """Return cache statistics.""" | |
| r = _get_redis() | |
| redis_ok = r is not None | |
| redis_info = {} | |
| if redis_ok: | |
| try: | |
| info = r.info("memory") | |
| redis_info = { | |
| "used_memory_human": info.get("used_memory_human", "N/A"), | |
| "connected_clients": r.info("clients").get("connected_clients", 0), | |
| } | |
| except Exception: | |
| pass | |
| return { | |
| "backend": "redis" if redis_ok else "memory", | |
| "redis": redis_info, | |
| "memory_entries": len(_memory_cache), | |
| } | |
| def close_cache(): | |
| """Close Redis connection.""" | |
| global _redis_client | |
| if _redis_client is not None: | |
| try: | |
| _redis_client.close() | |
| except Exception: | |
| pass | |
| _redis_client = None | |