Skip to content

Commit e6bcb63

Browse files
committed
perf: 使用@lru_cache缓存ip归属区域查询结果,避免重复调用ip归属区域查询接口以优化性能
1 parent 3961309 commit e6bcb63

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

dash-fastapi-backend/module_admin/annotation/log_annotation.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from functools import wraps
1+
from functools import wraps, lru_cache
22
from fastapi import Request
33
from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse
44
import inspect
@@ -52,21 +52,7 @@ async def wrapper(*args, **kwargs):
5252
oper_ip = request.headers.get('remote_addr') if request.headers.get('is_browser') == 'no' else request.headers.get('X-Forwarded-For')
5353
oper_location = '内网IP'
5454
if AppConfig.app_ip_location_query:
55-
try:
56-
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
57-
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
58-
if ip_result.status_code == 200:
59-
prov = ip_result.json().get('data').get('prov')
60-
city = ip_result.json().get('data').get('city')
61-
if prov or city:
62-
oper_location = f'{prov}-{city}'
63-
else:
64-
oper_location = '未知'
65-
else:
66-
oper_location = '未知'
67-
except Exception as e:
68-
oper_location = '未知'
69-
print(e)
55+
oper_location = get_ip_location(oper_ip)
7056
# 根据不同的请求类型使用不同的方法获取请求参数
7157
content_type = request.headers.get("Content-Type")
7258
if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type):
@@ -167,3 +153,26 @@ async def wrapper(*args, **kwargs):
167153
return wrapper
168154

169155
return decorator
156+
157+
158+
@lru_cache()
159+
def get_ip_location(oper_ip: str):
160+
"""
161+
查询ip归属区域
162+
:param oper_ip: 需要查询的ip
163+
:return: ip归属区域
164+
"""
165+
oper_location = '内网IP'
166+
try:
167+
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
168+
oper_location = '未知'
169+
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
170+
if ip_result.status_code == 200:
171+
prov = ip_result.json().get('data').get('prov')
172+
city = ip_result.json().get('data').get('city')
173+
if prov or city:
174+
oper_location = f'{prov}-{city}'
175+
except Exception as e:
176+
oper_location = '未知'
177+
print(e)
178+
return oper_location

0 commit comments

Comments
 (0)