File size: 672 Bytes
5129d6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from dataclasses import dataclass
import time
from asyncio import Lock


@dataclass
class Value:
    data: str
    birth: int
    ttl_ts: int


_store = {}
_lock = Lock()


def _now() -> int:
    return int(time.time())


async def create_cache(value: str, key: str, expire: int):
    async with _lock:
        _store[key] = Value(value, _now(), _now() + (expire or 0))


async def retrieve_cache(key: str):
    async with _lock:
        v = _store.get(key)
        if v:
            if v.ttl_ts < _now():
                del _store[key]
            else:
                # return stored data and age
                return v.data, _now() - v.birth
        return None, 0