File size: 1,068 Bytes
b5d8bfb
 
 
 
 
 
 
 
 
 
 
39b3598
b5d8bfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
37
38
"""
Tiny in-memory TTL cache. Nothing fancy -- this exists purely so that
repeated searches for the same query during development/demo don't
burn through the free SerpAPI monthly quota (100 searches/month).

Swap this out for Redis if you ever deploy at scale; for a personal
project / hackathon demo this is more than enough.
"""
import time
from typing import Any, Optional

from backend.config import CACHE_TTL_SECONDS


class TTLCache:
    def __init__(self, ttl_seconds: int = CACHE_TTL_SECONDS):
        self.ttl = ttl_seconds
        self._store: dict[str, tuple[float, Any]] = {}

    def get(self, key: str) -> Optional[Any]:
        entry = self._store.get(key)
        if not entry:
            return None
        expires_at, value = entry
        if time.time() > expires_at:
            self._store.pop(key, None)
            return None
        return value

    def set(self, key: str, value: Any) -> None:
        self._store[key] = (time.time() + self.ttl, value)

    def clear(self) -> None:
        self._store.clear()


search_cache = TTLCache()