This repository has been archived on 2023-10-01. You can view files and clone it, but cannot push or open issues or pull requests.
PyNyaaTa/pynyaata/cache/__init__.py

40 lines
840 B
Python
Raw Normal View History

2022-10-26 13:06:04 +00:00
from functools import wraps
2023-01-04 21:32:27 +00:00
from logging import error
2022-12-22 00:01:21 +00:00
from os import getenv
from typing import Optional
2022-10-26 13:06:04 +00:00
from pynyaata.cache.simple import SimpleCache
2023-01-06 17:19:59 +00:00
from pynyaata.types import Bridge, Cache
2022-12-22 00:01:21 +00:00
2022-10-26 13:06:04 +00:00
from redis import RedisError
2022-12-22 00:01:21 +00:00
REDIS_URL: Optional[str] = getenv("REDIS_URL")
2022-10-26 13:06:04 +00:00
client: Cache = SimpleCache()
2022-12-22 00:01:21 +00:00
2022-10-26 13:06:04 +00:00
if REDIS_URL:
try:
from pynyaata.cache.redis import RedisCache
client = RedisCache()
except RedisError as e:
2023-01-04 21:32:27 +00:00
error(e)
2022-10-26 13:06:04 +00:00
def cache_data(f):
@wraps(f)
2023-01-06 17:19:59 +00:00
async def wrapper(bridge: Bridge, query: str = "", page: int = 1):
2023-01-04 15:57:16 +00:00
key = f"pynyaata.{bridge.__class__.__name__}.{f.__name__}.{query}.{page}"
2023-01-06 17:19:59 +00:00
cached = client.get(key)
2022-10-26 13:06:04 +00:00
2023-01-06 17:19:59 +00:00
if cached:
return cached
2022-10-26 13:06:04 +00:00
2023-01-06 17:19:59 +00:00
reals = await f(bridge, query, page)
client.set(key, reals)
2022-10-26 13:06:04 +00:00
2023-01-06 17:19:59 +00:00
return reals
2022-10-26 13:06:04 +00:00
return wrapper