Spaces:
Running
Running
Download cache.py from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 2.04 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/cache.py
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/cache.py
2.04 kB
| import json | |
| import os | |
| import time | |
| from typing import Any | |
| import redis | |
| REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379") | |
| REDIS_FAILURE_COOLDOWN = 60.0 # Cooldown period in seconds when Redis is unreachable | |
| _redis_client = None | |
| _last_redis_failure: float = 0.0 | |
| def get_redis_client(): | |
| global _redis_client, _last_redis_failure | |
| if not REDIS_URL or REDIS_URL.lower() in ("none", "disabled", "false", ""): | |
| return None | |
| if _redis_client is not None: | |
| return _redis_client | |
| now = time.monotonic() | |
| if now - _last_redis_failure < REDIS_FAILURE_COOLDOWN: | |
| return None | |
| try: | |
| client = redis.Redis.from_url( | |
| REDIS_URL, | |
| decode_responses=True, | |
| socket_connect_timeout=0.2, | |
| socket_timeout=0.2, | |
| ) | |
| # Test connection with short ping | |
| client.ping() | |
| _redis_client = client | |
| return _redis_client | |
| except Exception: | |
| _redis_client = None | |
| _last_redis_failure = time.monotonic() | |
| return None | |
| def get_cache(key: str) -> Any | None: | |
| global _redis_client, _last_redis_failure | |
| client = get_redis_client() | |
| if client: | |
| try: | |
| val = client.get(key) | |
| if val: | |
| return json.loads(val) | |
| except Exception: | |
| _redis_client = None | |
| _last_redis_failure = time.monotonic() | |
| return None | |
| def set_cache(key: str, value: Any, ttl_seconds: int = 3600): | |
| global _redis_client, _last_redis_failure | |
| client = get_redis_client() | |
| if client: | |
| try: | |
| client.setex(key, ttl_seconds, json.dumps(value)) | |
| except Exception: | |
| _redis_client = None | |
| _last_redis_failure = time.monotonic() | |
| def delete_cache(key: str): | |
| global _redis_client, _last_redis_failure | |
| client = get_redis_client() | |
| if client: | |
| try: | |
| client.delete(key) | |
| except Exception: | |
| _redis_client = None | |
| _last_redis_failure = time.monotonic() | |