Buckets:
| from __future__ import annotations | |
| from time import time | |
| from typing import Any, NamedTuple | |
| class Cached(NamedTuple): | |
| value: Any | |
| expiry: float | |
| def older_than(self, seconds: float) -> bool: | |
| return time() - self.expiry > seconds | |
| class Cache: | |
| """ | |
| Small caching utility providing simple get/set interface (very much like redis) | |
| """ | |
| def __init__(self) -> None: | |
| self._values: dict[Any, Cached] = {} | |
| def value(self, key: str) -> Cached | None: | |
| return self._values.get(key) | |
| def get(self, key: str, default=None) -> Any | None: | |
| cached = self._values.get(key) | |
| if cached is not None: | |
| if cached.expiry > time(): | |
| return cached.value | |
| else: | |
| self._values.pop(key) | |
| return default | |
| def set(self, key: str, value: Any, expiry: float = 10): | |
| self._values[key] = Cached(value, time() + expiry) | |
| def pop(self, key: str, default=None) -> Any | None: | |
| cached = self._values.pop(key, None) | |
| if cached and cached.expiry > time(): | |
| return cached.value | |
| return default | |
| async def save_result(self, coro, key: str, expiry: float = 10): | |
| """ | |
| If `key` exists, return its value, otherwise call coro and cache its result | |
| """ | |
| cached = self.get(key) | |
| if cached: | |
| return cached | |
| else: | |
| value = await coro() | |
| self.set(key, value, expiry=expiry) | |
| return value | |
| async def invalidate_cache(self): | |
| ts = time() | |
| expired = [k for k, v in self._values.items() if v.expiry < ts] | |
| for k in expired: | |
| self._values.pop(k) | |
| cache = Cache() | |
Xet Storage Details
- Size:
- 1.72 kB
- Xet hash:
- 4e01ed653dfa7cbcb31fd4cd51e9a56fc9eb68400336812fffd86f00eda7004b
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.