From 52e92d50d11bdb3da37c809ed4b8ccd4386939d0 Mon Sep 17 00:00:00 2001 From: insistence <3055204202@qq.com> Date: Wed, 24 Apr 2024 10:03:52 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BD=BF=E7=94=A8@lru=5Fcache=E7=BC=93?= =?UTF-8?q?=E5=AD=98ip=E5=BD=92=E5=B1=9E=E5=8C=BA=E5=9F=9F=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E7=BB=93=E6=9E=9C=EF=BC=8C=E9=81=BF=E5=85=8D=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E8=B0=83=E7=94=A8ip=E5=BD=92=E5=B1=9E=E5=8C=BA?= =?UTF-8?q?=E5=9F=9F=E6=9F=A5=E8=AF=A2=E6=8E=A5=E5=8F=A3=E4=BB=A5=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../module_admin/annotation/log_annotation.py | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py b/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py index 079bfd0..e864391 100644 --- a/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py +++ b/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py @@ -1,4 +1,4 @@ -from functools import wraps +from functools import wraps, lru_cache from fastapi import Request from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse import inspect @@ -52,21 +52,7 @@ def log_decorator(title: str, business_type: int, log_type: Optional[str] = 'ope oper_ip = request.headers.get("X-Forwarded-For") oper_location = '内网IP' if AppConfig.app_ip_location_query: - try: - if oper_ip != '127.0.0.1' and oper_ip != 'localhost': - ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}') - if ip_result.status_code == 200: - prov = ip_result.json().get('data').get('prov') - city = ip_result.json().get('data').get('city') - if prov or city: - oper_location = f'{prov}-{city}' - else: - oper_location = '未知' - else: - oper_location = '未知' - except Exception as e: - oper_location = '未知' - print(e) + oper_location = get_ip_location(oper_ip) # 根据不同的请求类型使用不同的方法获取请求参数 content_type = request.headers.get("Content-Type") if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type): @@ -175,3 +161,26 @@ def log_decorator(title: str, business_type: int, log_type: Optional[str] = 'ope return wrapper return decorator + + +@lru_cache() +def get_ip_location(oper_ip: str): + """ + 查询ip归属区域 + :param oper_ip: 需要查询的ip + :return: ip归属区域 + """ + oper_location = '内网IP' + try: + if oper_ip != '127.0.0.1' and oper_ip != 'localhost': + oper_location = '未知' + ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}') + if ip_result.status_code == 200: + prov = ip_result.json().get('data').get('prov') + city = ip_result.json().get('data').get('city') + if prov or city: + oper_location = f'{prov}-{city}' + except Exception as e: + oper_location = '未知' + print(e) + return oper_location