Spaces:
Sleeping
Sleeping
| import logging | |
| from typing import Dict, Optional | |
| logger = logging.getLogger(__name__) | |
| class IPLocationService: | |
| """IP地理位置解析服务(降级版本)""" | |
| def __init__(self): | |
| pass | |
| def get_location(self, ip_address: str) -> Dict[str, Optional[str]]: | |
| """ | |
| 根据IP地址获取地理位置信息 | |
| Returns: | |
| { | |
| "country": "国家", | |
| "region": "地区/省份", | |
| "city": "城市", | |
| "latitude": "纬度", | |
| "longitude": "经度" | |
| } | |
| """ | |
| try: | |
| # 如果是本地IP,返回默认值 | |
| if self._is_private_ip(ip_address): | |
| return { | |
| "country": "中国", | |
| "region": "本地", | |
| "city": "本地", | |
| "latitude": "39.9042", | |
| "longitude": "116.4074" | |
| } | |
| # 降级:返回默认位置 | |
| return self._get_default_location() | |
| except Exception as e: | |
| logger.error(f"IP地理位置解析异常: {ip_address}, 错误: {str(e)}") | |
| return self._get_default_location() | |
| def _is_private_ip(self, ip: str) -> bool: | |
| """检查是否为私有IP地址""" | |
| if ip.startswith("127.") or ip.startswith("192.168.") or ip.startswith("10."): | |
| return True | |
| if ip.startswith("172."): | |
| parts = ip.split(".") | |
| if len(parts) >= 2: | |
| try: | |
| second_octet = int(parts[1]) | |
| if 16 <= second_octet <= 31: | |
| return True | |
| except ValueError: | |
| pass | |
| return False | |
| def _get_default_location(self) -> Dict[str, Optional[str]]: | |
| """返回默认位置""" | |
| return { | |
| "country": None, | |
| "region": None, | |
| "city": None, | |
| "latitude": None, | |
| "longitude": None | |
| } | |
| # 全局实例 | |
| ip_location_service = IPLocationService() | |