import inspect import json import logging from api.core.Gzip import gzip_zip, gzip_unzip from config.main import config logger = logging.getLogger('dcalc.redis_cache') def _read_cached(redis, key, without_gzip): content = redis.get(key) if content is None: return None return json.loads(content if without_gzip else gzip_unzip(content)) def _write_cached(redis, key, info, expire, without_gzip): content = json.dumps(info) if without_gzip else gzip_zip(json.dumps(info)) if expire > 0: redis.set(key, content, ex=expire) else: redis.set(key, content) async def _read_cached_async(redis, key, without_gzip): content = await redis.get(key) if content is None: return None return json.loads(content if without_gzip else gzip_unzip(content)) async def _write_cached_async(redis, key, info, expire, without_gzip): content = json.dumps(info) if without_gzip else gzip_zip(json.dumps(info)) if expire > 0: await redis.set(key, content, ex=expire) else: await redis.set(key, content) async def get_redis_info_async(redis, key, fun, expire=0, without_gzip=False): info = None if not config.DEBUG_MODE and redis: try: info = await _read_cached_async(redis, key, without_gzip) except Exception: logger.warning('read Redis cache failed key=%s', key, exc_info=True) info = None if info is None: if inspect.iscoroutinefunction(fun): info = await fun() else: info = fun() if not config.DEBUG_MODE and redis and info is not None: try: await _write_cached_async(redis, key, info, expire, without_gzip) except Exception: logger.warning('write Redis cache failed key=%s', key, exc_info=True) return info def get_redis_info(redis, key, fun, expire=0, without_gzip=False): info = None if not config.DEBUG_MODE and redis: try: info = _read_cached(redis, key, without_gzip) except Exception: logger.warning('read Redis cache failed key=%s', key, exc_info=True) info = None if info is None: info = fun() if not config.DEBUG_MODE and redis and info is not None: try: _write_cached(redis, key, info, expire, without_gzip) except Exception: logger.warning('write Redis cache failed key=%s', key, exc_info=True) return info