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

43 lines
854 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
from pynyaata.types import 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-04 21:32:27 +00:00
async def wrapper(*args, **kwargs):
2022-10-26 13:06:04 +00:00
bridge = args[0]
2023-01-04 15:57:16 +00:00
query = args[1]
page = args[2]
key = f"pynyaata.{bridge.__class__.__name__}.{f.__name__}.{query}.{page}"
2022-10-26 13:06:04 +00:00
ret = client.get(key)
if ret:
return ret
2023-01-04 21:32:27 +00:00
ret = await f(*args, **kwargs)
2022-10-26 13:06:04 +00:00
client.set(key, ret)
return ret
return wrapper