Skip to content

Commit 8c55d8c

Browse files
committed
refactor: 重构IP归属区域查询为异步调用
1 parent f5f4692 commit 8c55d8c

1 file changed

Lines changed: 13 additions & 11 deletions

File tree

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

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1+
import httpx
12
import inspect
23
import json
34
import os
4-
import requests
55
import time
6+
from async_lru import alru_cache
67
from datetime import datetime
78
from fastapi import Request
89
from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse
9-
from functools import lru_cache, wraps
10+
from functools import wraps
1011
from sqlalchemy.ext.asyncio import AsyncSession
1112
from typing import Any, Callable, Literal, Optional
1213
from user_agents import parse
@@ -78,7 +79,7 @@ async def wrapper(*args, **kwargs):
7879
)
7980
oper_location = '内网IP'
8081
if AppConfig.app_ip_location_query:
81-
oper_location = get_ip_location(oper_ip)
82+
oper_location = await get_ip_location(oper_ip)
8283
# 根据不同的请求类型使用不同的方法获取请求参数
8384
content_type = request.headers.get('Content-Type')
8485
if content_type and (
@@ -207,8 +208,8 @@ async def wrapper(*args, **kwargs):
207208
return wrapper
208209

209210

210-
@lru_cache()
211-
def get_ip_location(oper_ip: str):
211+
@alru_cache()
212+
async def get_ip_location(oper_ip: str):
212213
"""
213214
查询ip归属区域
214215
@@ -219,12 +220,13 @@ def get_ip_location(oper_ip: str):
219220
try:
220221
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
221222
oper_location = '未知'
222-
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
223-
if ip_result.status_code == 200:
224-
prov = ip_result.json().get('data').get('prov')
225-
city = ip_result.json().get('data').get('city')
226-
if prov or city:
227-
oper_location = f'{prov}-{city}'
223+
async with httpx.AsyncClient() as client:
224+
ip_result = await client.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
225+
if ip_result.status_code == 200:
226+
prov = ip_result.json().get('data', {}).get('prov')
227+
city = ip_result.json().get('data', {}).get('city')
228+
if prov or city:
229+
oper_location = f'{prov}-{city}'
228230
except Exception as e:
229231
oper_location = '未知'
230232
print(e)

0 commit comments

Comments
 (0)