mirror of
https://gitee.com/mao-peng/MangoTestingPlatform.git
synced 2025-12-06 11:59:15 +08:00
优化链接
This commit is contained in:
@@ -12,6 +12,7 @@ from django.core.handlers.asgi import ASGIRequest
|
||||
from rest_framework.response import Response
|
||||
from src.auto_test.auto_user.models import User
|
||||
from src.auto_test.auto_user.views.user_logs import UserLogsCRUD
|
||||
from django.db import close_old_connections
|
||||
|
||||
|
||||
class UserLogsMiddleWare(MiddlewareMixin):
|
||||
@@ -43,8 +44,12 @@ class UserLogsMiddleWare(MiddlewareMixin):
|
||||
user_name = request_data.get('username')
|
||||
if isinstance(user_name, list):
|
||||
user_name = user_name[0]
|
||||
# 确保在数据库操作前后关闭连接
|
||||
close_old_connections()
|
||||
user_id = User._default_manager.get(username=user_name).id
|
||||
close_old_connections()
|
||||
except User.DoesNotExist:
|
||||
close_old_connections()
|
||||
pass
|
||||
try:
|
||||
request_data = json.dumps(request_data, ensure_ascii=False)
|
||||
@@ -63,6 +68,9 @@ class UserLogsMiddleWare(MiddlewareMixin):
|
||||
self._save_user_logs_async(log_entry)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
# 确保在异步处理完成后关闭所有数据库连接
|
||||
close_old_connections()
|
||||
|
||||
def _capture_request_data(self, request: ASGIRequest, response: Response) -> dict:
|
||||
if request.method == 'POST' or request.method == 'PUT':
|
||||
@@ -115,6 +123,10 @@ class UserLogsMiddleWare(MiddlewareMixin):
|
||||
def _save_user_logs_async(self, log_entry: dict) -> None:
|
||||
"""异步保存用户日志到数据库"""
|
||||
try:
|
||||
# 确保在数据库操作前后关闭连接
|
||||
close_old_connections()
|
||||
UserLogsCRUD.inside_post(log_entry)
|
||||
close_old_connections()
|
||||
except Exception as e:
|
||||
close_old_connections()
|
||||
print(e)
|
||||
|
||||
@@ -126,10 +126,12 @@ if not IS_SQLITE:
|
||||
'connect_timeout': 20, # 增加到20秒
|
||||
'read_timeout': 60, # 增加读取超时到60秒
|
||||
'write_timeout': 60, # 增加写入超时到60秒
|
||||
'init_command': "SET sql_mode='STRICT_TRANS_TABLES', wait_timeout=28800",
|
||||
'init_command': "SET sql_mode='STRICT_TRANS_TABLES', wait_timeout=300",
|
||||
'isolation_level': 'READ COMMITTED',
|
||||
'autocommit': True,
|
||||
},
|
||||
'CONN_MAX_AGE': 300, # 5分钟连接最大存活时间
|
||||
'CONN_HEALTH_CHECKS': True, # Django 4.1+ 健康检查
|
||||
}
|
||||
}
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user