From ec908f0dea7f0229c417b0af95e77d5d0d5ccee5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?I=E5=A4=8F?= Date: Thu, 2 Jun 2022 20:19:54 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96=EF=BC=8C?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=BC=93=E5=AD=98=E5=87=BD=E6=95=B0=E6=8F=90?= =?UTF-8?q?=E5=89=8D=E5=A4=B1=E6=95=88=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fir_ser/common/base/magic.py | 26 +++++++++++++++++--------- fir_ser/common/core/exception.py | 7 ++++++- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/fir_ser/common/base/magic.py b/fir_ser/common/base/magic.py index 3461e41..6724fa0 100644 --- a/fir_ser/common/base/magic.py +++ b/fir_ser/common/base/magic.py @@ -173,7 +173,14 @@ def magic_call_in_times(call_time=24 * 3600, call_limit=6, key=None): class MagicCacheData(object): @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): @wraps(func) def wrapper(*args, **kwargs): @@ -183,22 +190,23 @@ class MagicCacheData(object): else: cache_key = f'{cache_key}_{func.__name__}' + n_time = time.time() 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}") - return res + return res['data'] else: - start_time = time.time() try: - res = func(*args, **kwargs) + data = func(*args, **kwargs) + res = {'c_time': n_time, 'data': data} cache.set(cache_key, res, cache_time) 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: - logger.info( - f"exec {func} failed. time:{time.time() - start_time} cache_key:{cache_key} Exception:{e}") + logger.error( + f"exec {func} failed. time:{time.time() - n_time} cache_key:{cache_key} Exception:{e}") - return res + return res['data'] return wrapper diff --git a/fir_ser/common/core/exception.py b/fir_ser/common/core/exception.py index fc67bd1..3cdc4e6 100644 --- a/fir_ser/common/core/exception.py +++ b/fir_ser/common/core/exception.py @@ -30,4 +30,9 @@ def common_exception_handler(exc, context): if not ret: # drf内置处理不了,丢给django 的,我们自己来处理 return ApiResponse(msg='error', result=str(exc), code=5000) 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)