feat: 修改登录日志为异步任务

This commit is contained in:
XIE7654
2025-10-02 14:27:20 +08:00
parent 9b724f2687
commit 7099cbbc1e
2 changed files with 56 additions and 27 deletions

View File

@@ -1,14 +1,55 @@
# 某个 app 目录下的 tasks.py
import requests
from celery import shared_task
from django.utils import timezone
from system.models import LoginLog, User
@shared_task
def add(x, y):
return x + y
@shared_task
def sync_temu_order():
pass
@shared_task
def sync_temu_shipping():
pass
def update_user_login_info(user_id, client_ip, user_agent):
# 更新用户登录信息
user = User.objects.get(id=user_id)
user.login_ip = client_ip
user.last_login = timezone.now()
user.save(update_fields=['login_ip', 'last_login'])
# 获取地理位置信息
location_info = get_location_from_ip(client_ip)
# 记录登录日录
LoginLog.objects.create(
username=user.username,
result=LoginLog.LoginResult.SUCCESS,
user_ip=client_ip,
location=location_info,
user_agent=user_agent
)
def get_location_from_ip(ip):
"""根据IP地址获取地理位置信息"""
try:
if ip in ['127.0.0.1', 'localhost']:
return "本地网络"
url = f"http://ip-api.com/json/{ip}?lang=zh-CN"
try:
response = requests.get(url, timeout=5)
data = response.json()
if data["status"] == "success":
location_parts = [data["city"], data["regionName"], data["country"]]
return ', '.join(location_parts) if location_parts else "未知位置"
else:
return f"IP {ip} 查询失败:{data['message']}"
except Exception as e:
return f"IP {ip} 连接错误:{str(e)}"
except Exception as e:
import logging
logger = logging.getLogger(__name__)
logger.error(f"获取IP地址位置信息失败: {str(e)}")
return "位置获取失败"