1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
""" ------------------------------------------------
describe: watcher 用于API计时打点,写入request表
base_info: __author__ = "PyGo" __time__ = "2022/8/26 23:02" __version__ = "v.1.0.0" __mail__ = "gaoming971366@163.com" __blog__ = "www.pygo2.top" __project__ = "open2lisapi"
usage: from flask import request @watcher(watcher_args=request) watcher_args参数为request对象,里面包含blueprint, endpoint, method, path, header等请求参数
design:
reference urls:
python version: python3
Enjoy the good life everyday!!! Life is short, I use python.
------------------------------------------------ """
from datetime import datetime from functools import wraps from pprint import pprint
from deploy.utils.logger import logger as LOG from deploy.utils.utils import get_rtx_id from deploy.services.request import RequestService
request_service = RequestService() GLOBAL_NEW_ENDPOINR = [ 'dashboard.pan', 'dashboard.pan_chart', 'dashboard.index', 'auth.user_list', 'info.dict_list' ]
def __add_request(request, cost, rtx=None): """ API request information to insert into request table :param request: API request object parameters :param cost: API run time, unit is second :param rtx: request user rtx-id - 1.request get "X-Rtx-Id" - 2.no request by manual set """ rtx_id = get_rtx_id(request) or rtx if not rtx_id: return False method = getattr(request, 'method') if method and str(method).upper() not in ['GET', 'POST']: return False if hasattr(request, 'endpoint') and getattr(request, 'endpoint') in GLOBAL_NEW_ENDPOINR: RequestService().add_request(request=request, cost=cost, rtx=rtx_id) else: request_service.add_request(request=request, cost=cost, rtx=rtx_id)
def watcher(watcher_args): def _watcher(fn): @wraps(fn) def _wrapper(*args, **kwargs): start = datetime.now() res = fn(*args, **kwargs) end = datetime.now() cost = round((end-start).microseconds * pow(0.1, 6), 4) if watcher_args: __add_request(request=watcher_args, cost=cost) LOG.info('@Watcher [%s] is run: %s' % (getattr(watcher_args, 'endpoint') or fn.__name__, cost)) return res
return _wrapper return _watcher
|