PamGram/core/services/wiki/cache.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

38 lines
1.1 KiB
Python
Raw Normal View History

import ujson as json
2022-07-26 10:07:31 +00:00
from core.base_service import BaseService
from core.dependence.redisdb import RedisDB
from modules.wiki.base import Model
2022-07-26 10:07:31 +00:00
__all__ = ["WikiCache"]
2022-07-26 10:07:31 +00:00
class WikiCache(BaseService.Component):
2022-07-26 10:07:31 +00:00
def __init__(self, redis: RedisDB):
self.client = redis.client
self.qname = "wiki"
async def set(self, key: str, value):
qname = f"{self.qname}:{key}"
if isinstance(value, Model):
value = value.json()
elif isinstance(value, (dict, list)):
value = json.dumps(value)
await self.client.set(qname, value)
2022-07-26 10:07:31 +00:00
async def delete(self, key: str):
qname = f"{self.qname}:{key}"
2022-07-26 10:07:31 +00:00
await self.client.delete(qname)
async def get(self, key: str) -> dict:
qname = f"{self.qname}:{key}"
# noinspection PyBroadException
try:
result = json.loads(await self.client.get(qname))
2022-10-11 06:45:07 +00:00
except Exception: # pylint: disable=W0703
result = []
if isinstance(result, list) and len(result) > 0:
for num, item in enumerate(result):
result[num] = json.loads(item)
return result