feat(ip_local_util): 使用httpx替换requests以支持异步HTTP请求

为了提高IP归属地查询的性能和响应速度,将requests替换为httpx,并引入异步HTTP请求。同时,添加了备用API的注释以供未来使用。
This commit is contained in:
zhangtao
2025-05-18 22:43:19 +08:00
parent 27c6249fc4
commit 462b7f8896
2 changed files with 21 additions and 25 deletions
+19 -24
View File
@@ -2,6 +2,7 @@
import re import re
import requests import requests
import httpx
from app.core.logger import logger from app.core.logger import logger
@@ -42,31 +43,25 @@ class IpLocalUtil:
return '内网IP' return '内网IP'
try: try:
# 优先使用百度API # 百度API失败,使用其他API
ip_result = requests.get( async with httpx.AsyncClient() as client:
f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={ip}', response = await client.get(
timeout=5 f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={ip}',
) timeout=5
result = ip_result.json() )
if result['code']== 'Success': if response.status_code == 200:
data = response.json().get('data', {})
return f"【{data.get('owner','')}】-{data.get('country','')}-{data.get('prov','')}-{data.get('city','')}-{data.get('district','')}"
data = result['data'] # 使用ip-api.com API获取IP归属地信息
logger.info(f"获取IP归属地成功: {data}") # async with httpx.AsyncClient() as client:
# "continent": "亚洲", # response = await client.get(
# "country": "中国", # f'http://ip-api.com/json/{ip}?lang=zh-CN',
# "zipcode": "710061", # timeout=10
# "owner": "中国移动", # )
# "isp": "中国移动", # if response.status_code == 200:
# "adcode": "610113", # result = response.json()
# "prov": "陕西省", # return f"【{result.get('isp','')}】-{result.get('country','')}-{result.get('regionName','')}-{result.get('city','')}"
# "city": "西安市",
# "district": "雁塔区"
country = data['country']
owner = data['owner']
prov = data['prov']
city = data['city']
district = data['district']
return f'【{owner}】-{country}-{prov}-{city}-{district}'
except Exception as e: except Exception as e:
logger.error(f"获取IP归属地失败: {e}") logger.error(f"获取IP归属地失败: {e}")
+1
View File
@@ -6,6 +6,7 @@ uvicorn==0.30.6 # uvicorn web 框架
websockets==14.2 # websocket 框架 websockets==14.2 # websocket 框架
gunicorn==23.0.0 # 协程框架 gunicorn==23.0.0 # 协程框架
# celery==5.4.0 # 任务队列(移除,使用APScheduler) # celery==5.4.0 # 任务队列(移除,使用APScheduler)
httpx==0.28.1 # HTTP 客户端
croniter==6.0.0 # 实现cron表达式验证和解析执行计划 croniter==6.0.0 # 实现cron表达式验证和解析执行计划
pandas==2.2.2 # 数据处理 pandas==2.2.2 # 数据处理
openpyxl==3.1.5 # Excel openpyxl==3.1.5 # Excel