fix: location_info

This commit is contained in:
XIE7654
2025-09-09 13:41:43 +08:00
parent b1dd010c7f
commit aaace900a6

View File

@@ -1,3 +1,4 @@
import requests
from django.db.models import Prefetch, F from django.db.models import Prefetch, F
from django.utils import timezone from django.utils import timezone
from rest_framework import serializers from rest_framework import serializers
@@ -62,8 +63,8 @@ class UserLogin(ObtainAuthToken):
client_ip = get_client_ip(request) client_ip = get_client_ip(request)
# 获取IP地址的地理位置信息 # 获取IP地址的地理位置信息
# location_info = self.get_location_from_ip(client_ip) location_info = self.get_location_from_ip(client_ip)
location_info = '' # location_info = ''
# 更新登录IP和登录时间 # 更新登录IP和登录时间
user.login_ip = client_ip user.login_ip = client_ip
@@ -87,27 +88,27 @@ class UserLogin(ObtainAuthToken):
"message": "ok" "message": "ok"
}) })
def get_location_from_ip(self, ip_address): def get_location_from_ip(self, ip):
"""根据IP地址获取地理位置信息""" """根据IP地址获取地理位置信息"""
try: try:
# 对于本地IP地址返回默认值 # 对于本地IP地址返回默认值
if ip_address in ['127.0.0.1', 'localhost']: if ip in ['127.0.0.1', 'localhost']:
return "本地网络" return "本地网络"
# 查询IP地址信息 # 查询IP地址信息
response = DbIpCity.get(ip_address, api_key='free') # 免费接口无需密钥返回JSON格式数据
url = f"http://ip-api.com/json/{ip}?lang=zh-CN" # lang=zh-CN 确保返回中文
# 构建地区信息字符串 try:
location_parts = [] response = requests.get(url, timeout=5)
if response.city: data = response.json()
location_parts.append(response.city) if data["status"] == "success": # 接口返回成功
if response.region: # 构建地区信息字符串
location_parts.append(response.region) location_parts = [data["city"], data["regionName"],data["country"]]
if response.country: return ', '.join(location_parts) if location_parts else "未知位置"
location_parts.append(response.country) else:
return f"IP {ip} 查询失败:{data['message']}"
return ', '.join(location_parts) if location_parts else "未知位置" except Exception as e:
return f"IP {ip} 连接错误:{str(e)}"
except Exception as e: except Exception as e:
# 记录错误日志 # 记录错误日志
import logging import logging