1+ import httpx
12import inspect
23import json
34import os
4- import requests
55import time
6+ from async_lru import alru_cache
67from datetime import datetime
78from fastapi import Request
89from fastapi .responses import JSONResponse , ORJSONResponse , UJSONResponse
9- from functools import lru_cache , wraps
10+ from functools import wraps
1011from sqlalchemy .ext .asyncio import AsyncSession
1112from typing import Any , Callable , Literal , Optional
1213from 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