代码优化,增加缓存函数提前失效参数

dependabot/npm_and_yarn/fir_admin/shell-quote-1.7.3
I夏 3 years ago
parent 47abaf61f5
commit ec908f0dea
  1. 26
      fir_ser/common/base/magic.py
  2. 7
      fir_ser/common/core/exception.py

@ -173,7 +173,14 @@ def magic_call_in_times(call_time=24 * 3600, call_limit=6, key=None):
class MagicCacheData(object): class MagicCacheData(object):
@staticmethod @staticmethod
def make_cache(cache_time=60 * 10, key=None): def make_cache(cache_time=60 * 10, invalid_time=0, key=None):
"""
:param cache_time: 数据缓存的时候单位秒
:param invalid_time: 数据缓存提前失效时间单位秒该cache有效时间为 cache_time-invalid_time
:param key: cache唯一标识默认为所装饰函数名称
:return:
"""
def decorator(func): def decorator(func):
@wraps(func) @wraps(func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
@ -183,22 +190,23 @@ class MagicCacheData(object):
else: else:
cache_key = f'{cache_key}_{func.__name__}' cache_key = f'{cache_key}_{func.__name__}'
n_time = time.time()
res = cache.get(cache_key) res = cache.get(cache_key)
if res: if res and n_time - res.get('c_time', n_time) < cache_time - invalid_time:
logger.info(f"exec {func} finished. cache_key:{cache_key} cache data exist result:{res}") logger.info(f"exec {func} finished. cache_key:{cache_key} cache data exist result:{res}")
return res return res['data']
else: else:
start_time = time.time()
try: try:
res = func(*args, **kwargs) data = func(*args, **kwargs)
res = {'c_time': n_time, 'data': data}
cache.set(cache_key, res, cache_time) cache.set(cache_key, res, cache_time)
logger.info( logger.info(
f"exec {func} finished. time:{time.time() - start_time} cache_key:{cache_key} result:{res}") f"exec {func} finished. time:{time.time() - n_time} cache_key:{cache_key} result:{res}")
except Exception as e: except Exception as e:
logger.info( logger.error(
f"exec {func} failed. time:{time.time() - start_time} cache_key:{cache_key} Exception:{e}") f"exec {func} failed. time:{time.time() - n_time} cache_key:{cache_key} Exception:{e}")
return res return res['data']
return wrapper return wrapper

@ -30,4 +30,9 @@ def common_exception_handler(exc, context):
if not ret: # drf内置处理不了,丢给django 的,我们自己来处理 if not ret: # drf内置处理不了,丢给django 的,我们自己来处理
return ApiResponse(msg='error', result=str(exc), code=5000) return ApiResponse(msg='error', result=str(exc), code=5000)
else: else:
return ApiResponse(msg='error', status=ret.status_code, **ret.data, ) msg = ret.data.get('msg')
if not msg:
msg = 'error'
else:
del ret.data['msg']
return ApiResponse(msg=msg, status=ret.status_code, **ret.data)

Loading…
Cancel
Save