|
1 | | -from functools import wraps |
| 1 | +from functools import wraps, lru_cache |
2 | 2 | from fastapi import Request |
3 | 3 | from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse |
4 | 4 | import inspect |
@@ -52,21 +52,7 @@ async def wrapper(*args, **kwargs): |
52 | 52 | oper_ip = request.headers.get('remote_addr') if request.headers.get('is_browser') == 'no' else request.headers.get('X-Forwarded-For') |
53 | 53 | oper_location = '内网IP' |
54 | 54 | 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) |
70 | 56 | # 根据不同的请求类型使用不同的方法获取请求参数 |
71 | 57 | content_type = request.headers.get("Content-Type") |
72 | 58 | 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): |
167 | 153 | return wrapper |
168 | 154 |
|
169 | 155 | 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