mirror of
https://github.com/ddCat-main/cursor-auto-register.git
synced 2025-12-24 13:38:01 +08:00
fix:修复重启系统报错 #35
This commit is contained in:
53
api.py
53
api.py
@@ -1317,38 +1317,47 @@ async def update_config(config: ConfigModel):
|
||||
return {"success": False, "message": f"更新配置失败: {str(e)}"}
|
||||
|
||||
|
||||
# 添加重启API端点
|
||||
# 优化重启API功能,解决卡住问题
|
||||
@app.post("/restart", tags=["System"])
|
||||
async def restart_service():
|
||||
"""重启应用服务"""
|
||||
try:
|
||||
info("收到重启服务请求")
|
||||
|
||||
# 创建一个子进程来执行重启
|
||||
if sys.platform == 'win32':
|
||||
cmd = 'powershell -Command "Start-Sleep -s 2; Start-Process python -ArgumentList \'api.py\'"'
|
||||
# 使用更简单的重启方法 - 通过reload环境变量触发uvicorn重载
|
||||
# 1. 修改.env文件,添加/更新一个时间戳,触发热重载
|
||||
env_path = os.path.join(os.getcwd(), ".env")
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
# 读取现有.env文件
|
||||
if os.path.exists(env_path):
|
||||
with open(env_path, "r", encoding="utf-8") as f:
|
||||
env_lines = f.read().splitlines()
|
||||
else:
|
||||
cmd = 'bash -c "sleep 2 && nohup python api.py > /dev/null 2>&1 &"'
|
||||
env_lines = []
|
||||
|
||||
# 启动新进程
|
||||
import subprocess
|
||||
subprocess.Popen(cmd, shell=True)
|
||||
|
||||
# 准备在2秒后关闭当前进程
|
||||
async def shutdown():
|
||||
await asyncio.sleep(2)
|
||||
info("执行服务重启...")
|
||||
for proc in psutil.process_children(psutil.Process()):
|
||||
try:
|
||||
proc.terminate()
|
||||
except:
|
||||
pass
|
||||
os._exit(0) # 强制退出当前进程
|
||||
# 更新或添加RESTART_TIMESTAMP变量
|
||||
timestamp_found = False
|
||||
for i, line in enumerate(env_lines):
|
||||
if line.startswith("RESTART_TIMESTAMP="):
|
||||
env_lines[i] = f"RESTART_TIMESTAMP={timestamp}"
|
||||
timestamp_found = True
|
||||
break
|
||||
|
||||
if not timestamp_found:
|
||||
env_lines.append(f"RESTART_TIMESTAMP={timestamp}")
|
||||
|
||||
# 启动关闭任务
|
||||
asyncio.create_task(shutdown())
|
||||
# 写回.env文件
|
||||
with open(env_path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(env_lines))
|
||||
|
||||
info(f"已更新重启时间戳: {timestamp}")
|
||||
|
||||
return {"success": True, "message": "服务正在重启,请稍候..."}
|
||||
# 仅提示用户手动刷新页面
|
||||
return {
|
||||
"success": True,
|
||||
"message": "配置已更新,请手动刷新页面以应用更改。"
|
||||
}
|
||||
except Exception as e:
|
||||
error(f"重启服务失败: {str(e)}")
|
||||
error(traceback.format_exc())
|
||||
|
||||
3
restart.sh
Executable file
3
restart.sh
Executable file
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
sleep 1
|
||||
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3 /Users/catdd/Desktop/work/ai/cursor-auto-register/api.py > restart.log 2>&1 &
|
||||
@@ -167,9 +167,10 @@ let filteredAccounts = [];
|
||||
let refreshTimer;
|
||||
|
||||
// 显示加载遮罩
|
||||
function showLoading() {
|
||||
function showLoading(message = '加载中,请稍候...') {
|
||||
const loadingOverlay = document.getElementById('loading-overlay');
|
||||
loadingOverlay.classList.add('show');
|
||||
$("#loading-overlay p").text(message);
|
||||
}
|
||||
|
||||
// 隐藏加载遮罩
|
||||
@@ -1308,60 +1309,34 @@ function showConfirmDialog(title, message, confirmCallback) {
|
||||
});
|
||||
}
|
||||
|
||||
// 添加重启服务函数
|
||||
// 更新重启服务函数
|
||||
function restartService() {
|
||||
showLoading();
|
||||
const loadingText = "服务正在重启,请稍候...";
|
||||
$("#loading-overlay p").text(loadingText);
|
||||
showLoading('服务正在重新配置,请稍候...');
|
||||
|
||||
$.ajax({
|
||||
url: '/restart',
|
||||
method: 'POST',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
// 设置一个定时器,每3秒尝试检查服务是否已重启
|
||||
let checkCount = 0;
|
||||
const maxChecks = 10; // 最多等待30秒
|
||||
// 显示成功消息
|
||||
hideLoading();
|
||||
showAlert('success', response.message || '服务配置已更新,正在刷新页面...');
|
||||
|
||||
const checkInterval = setInterval(function() {
|
||||
checkCount++;
|
||||
if (checkCount > maxChecks) {
|
||||
clearInterval(checkInterval);
|
||||
hideLoading();
|
||||
showAlert('warning', '服务重启时间过长,请手动刷新页面');
|
||||
return;
|
||||
}
|
||||
|
||||
// 尝试请求API检查服务是否可用
|
||||
$.ajax({
|
||||
url: '/accounts?page=1&per_page=1',
|
||||
method: 'GET',
|
||||
timeout: 2000,
|
||||
success: function() {
|
||||
clearInterval(checkInterval);
|
||||
hideLoading();
|
||||
showAlert('success', '服务已成功重启');
|
||||
// 重新加载页面以获取最新配置
|
||||
setTimeout(function() {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
},
|
||||
error: function() {
|
||||
// 服务未就绪,继续等待
|
||||
console.log('等待服务重启...');
|
||||
}
|
||||
});
|
||||
// 延迟3秒后刷新页面
|
||||
setTimeout(function() {
|
||||
window.location.reload();
|
||||
}, 3000);
|
||||
} else {
|
||||
hideLoading();
|
||||
showAlert('danger', '重启服务失败: ' + response.message);
|
||||
showAlert('danger', '重启服务失败: ' + (response.message || '未知错误'));
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
// 请求失败可能意味着服务已开始重启
|
||||
// 设置检查间隔
|
||||
error: function(xhr) {
|
||||
hideLoading();
|
||||
showAlert('danger', '重启服务请求失败,请手动刷新页面');
|
||||
|
||||
// 延迟5秒后尝试刷新页面
|
||||
setTimeout(function() {
|
||||
// 尝试重新加载页面
|
||||
window.location.reload();
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user