Bases: BaseCache
Memory Cache.
This cache lives in-memory, be aware of memory footprint when caching large responses.
Example:
Source code in pulsefire/caches.py
| class MemoryCache(BaseCache):
"""Memory Cache.
This cache lives in-memory, be aware of memory footprint when caching large responses.
Example:
```python
MemoryCache()
```
"""
cache: dict[str, tuple[Any, float]]
def __init__(self) -> None:
self.cache = {}
self.last_expired = time.time()
async def get[T](self, key: str) -> T:
value, expire = self.cache[key]
if time.time() > expire:
self.cache.pop(key, None)
raise KeyError(key)
return value
async def set(self, key: str, value: Any, ttl: float) -> None:
if ttl <= 0:
return
self.cache[key] = [value, time.time() + ttl]
if time.time() - self.last_expired > 60:
self.last_expired = time.time()
for old_key, (_, expire) in self.cache.items():
if time.time() > expire:
self.cache.pop(old_key, None)
async def clear(self) -> None:
self.cache.clear()
|
Attributes
cache
instance-attribute
cache: dict[str, tuple[Any, float]] = {}
last_expired
instance-attribute
Functions
__init__
Source code in pulsefire/caches.py
| def __init__(self) -> None:
self.cache = {}
self.last_expired = time.time()
|
get
async
Source code in pulsefire/caches.py
| async def get[T](self, key: str) -> T:
value, expire = self.cache[key]
if time.time() > expire:
self.cache.pop(key, None)
raise KeyError(key)
return value
|
set
async
set(key: str, value: Any, ttl: float) -> None
Source code in pulsefire/caches.py
| async def set(self, key: str, value: Any, ttl: float) -> None:
if ttl <= 0:
return
self.cache[key] = [value, time.time() + ttl]
if time.time() - self.last_expired > 60:
self.last_expired = time.time()
for old_key, (_, expire) in self.cache.items():
if time.time() > expire:
self.cache.pop(old_key, None)
|
clear
async
Source code in pulsefire/caches.py
| async def clear(self) -> None:
self.cache.clear()
|