feat(initialization): 更新 Python 版本并优化初始化流程

-将 Python 版本从 3.13.0 更改为3.12.0
- 添加路由守卫,确保在生产环境中也能正确进入初始化页面
- 在初始化页面中增加服务启动相关逻辑
- 优化环境检查和启动服务的代码结构
- 调整后端服务启动方式,增加调试用的强制启动功能
This commit is contained in:
2025-08-07 16:09:00 +08:00
parent 6aca142696
commit e7f898f357
3 changed files with 148 additions and 29 deletions

View File

@@ -13,11 +13,11 @@ export function setMainWindow(window: BrowserWindow) {
// Python镜像源URL映射 // Python镜像源URL映射
const pythonMirrorUrls = { const pythonMirrorUrls = {
official: 'https://www.python.org/ftp/python/3.13.0/python-3.13.0-embed-amd64.zip', official: 'https://www.python.org/ftp/python/3.12.0/python-3.12.0-embed-amd64.zip',
tsinghua: 'https://mirrors.tuna.tsinghua.edu.cn/python/3.13.0/python-3.13.0-embed-amd64.zip', tsinghua: 'https://mirrors.tuna.tsinghua.edu.cn/python/3.12.0/python-3.12.0-embed-amd64.zip',
ustc: 'https://mirrors.ustc.edu.cn/python/3.13.0/python-3.13.0-embed-amd64.zip', ustc: 'https://mirrors.ustc.edu.cn/python/3.12.0/python-3.12.0-embed-amd64.zip',
huawei: 'https://mirrors.huaweicloud.com/repository/toolkit/python/3.13.0/python-3.13.0-embed-amd64.zip', huawei: 'https://mirrors.huaweicloud.com/repository/toolkit/python/3.12.0/python-3.12.0-embed-amd64.zip',
aliyun: 'https://mirrors.aliyun.com/python-release/windows/python-3.13.0-embed-amd64.zip' aliyun: 'https://mirrors.aliyun.com/python-release/windows/python-3.12.0-embed-amd64.zip'
} }
// 检查pip是否已安装 // 检查pip是否已安装
@@ -200,7 +200,7 @@ export async function downloadPython(appRoot: string, mirror = 'ustc'): Promise<
const stats = fs.statSync(zipPath) const stats = fs.statSync(zipPath)
console.log(`Python压缩包大小: ${stats.size} bytes (${(stats.size / 1024 / 1024).toFixed(2)} MB)`) console.log(`Python压缩包大小: ${stats.size} bytes (${(stats.size / 1024 / 1024).toFixed(2)} MB)`)
// Python 3.13.0嵌入式版本应该大约30MB如果小于5MB可能是无效文件 // Python 3.12.0嵌入式版本应该大约30MB如果小于5MB可能是无效文件
if (stats.size < 5 * 1024 * 1024) { // 5MB if (stats.size < 5 * 1024 * 1024) { // 5MB
fs.unlinkSync(zipPath) // 删除无效文件 fs.unlinkSync(zipPath) // 删除无效文件
throw new Error(`Python下载文件大小异常: ${stats.size} bytes (${(stats.size / 1024).toFixed(2)} KB),可能是镜像站返回的错误页面或无效文件`) throw new Error(`Python下载文件大小异常: ${stats.size} bytes (${(stats.size / 1024).toFixed(2)} KB),可能是镜像站返回的错误页面或无效文件`)
@@ -233,7 +233,7 @@ export async function downloadPython(appRoot: string, mirror = 'ustc'): Promise<
console.log(`删除临时文件: ${zipPath}`) console.log(`删除临时文件: ${zipPath}`)
// 启用 site-packages 支持 // 启用 site-packages 支持
const pthFile = path.join(pythonPath, 'python313._pth') const pthFile = path.join(pythonPath, 'python312._pth')
if (fs.existsSync(pthFile)) { if (fs.existsSync(pthFile)) {
let content = fs.readFileSync(pthFile, 'utf-8') let content = fs.readFileSync(pthFile, 'utf-8')
content = content.replace(/^#import site/m, 'import site') content = content.replace(/^#import site/m, 'import site')
@@ -404,7 +404,7 @@ export async function startBackend(appRoot: string): Promise<{ success: boolean;
try { try {
const pythonPath = path.join(appRoot, 'environment', 'python', 'python.exe') const pythonPath = path.join(appRoot, 'environment', 'python', 'python.exe')
const backendPath = path.join(appRoot) const backendPath = path.join(appRoot)
const mainPyPath = path.join(backendPath, 'app','main.py') const mainPyPath = path.join(backendPath,'main.py')
// 检查文件是否存在 // 检查文件是否存在
if (!fs.existsSync(pythonPath)) { if (!fs.existsSync(pythonPath)) {
@@ -414,9 +414,11 @@ export async function startBackend(appRoot: string): Promise<{ success: boolean;
throw new Error('后端主文件不存在') throw new Error('后端主文件不存在')
} }
console.log(`启动后端指令: "${pythonPath}" "${mainPyPath}"cwd: ${appRoot}`)
// 启动后端进程 // 启动后端进程
const backendProcess = spawn(pythonPath, [mainPyPath], { const backendProcess = spawn(pythonPath, [mainPyPath], {
cwd: backendPath, cwd: appRoot,
stdio: 'pipe' stdio: 'pipe'
}) })
@@ -433,7 +435,19 @@ export async function startBackend(appRoot: string): Promise<{ success: boolean;
console.log('Backend output:', output) console.log('Backend output:', output)
// 检查是否包含启动成功的标志 // 检查是否包含启动成功的标志
if (output.includes('uvicorn') || output.includes('8000')) { if (output.includes('Uvicorn running') || output.includes('8000')) {
clearTimeout(timeout)
resolve()
}
})
// ✅ 重要:也要监听 stderr
backendProcess.stderr?.on('data', (data) => {
const output = data.toString()
console.error('Backend error:', output) // 保留原有日志
// ✅ 在 stderr 中也检查启动标志
if (output.includes('Uvicorn running') || output.includes('8000')) {
clearTimeout(timeout) clearTimeout(timeout)
resolve() resolve()
} }

View File

@@ -4,7 +4,9 @@ import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [ const routes: RouteRecordRaw[] = [
{ {
path: '/', path: '/',
redirect: '/initialization', redirect: () => {
return '/initialization'
},
}, },
{ {
path: '/initialization', path: '/initialization',
@@ -85,4 +87,23 @@ const router = createRouter({
routes, routes,
}) })
// 添加路由守卫,确保在生产环境中也能正确进入初始化页面
router.beforeEach((to, from, next) => {
console.log('路由守卫:', { to: to.path, from: from.path })
// 如果访问的不是初始化页面,且没有初始化标记,则重定向到初始化页面
if (to.path !== '/initialization') {
const isInitialized = localStorage.getItem('app-initialized')
console.log('检查初始化状态:', isInitialized)
if (!isInitialized) {
console.log('应用未初始化,重定向到初始化页面')
next('/initialization')
return
}
}
next()
})
export default router export default router

View File

@@ -65,7 +65,7 @@
<div v-if="currentStep === 1" class="step-panel"> <div v-if="currentStep === 1" class="step-panel">
<h3>Python 运行环境</h3> <h3>Python 运行环境</h3>
<div v-if="!pythonInstalled" class="install-section"> <div v-if="!pythonInstalled" class="install-section">
<p>需要安装 Python 3.13.0 运行环境64位嵌入式版本</p> <p>需要安装 Python 3.12.0 运行环境64位嵌入式版本</p>
<div class="mirror-grid"> <div class="mirror-grid">
<div <div
@@ -223,8 +223,31 @@
{{ getNextButtonText() }} {{ getNextButtonText() }}
</a-button> </a-button>
<!-- 第6步启动服务按钮 -->
<a-button <a-button
v-if="currentStep === 5 && allCompleted" v-if="currentStep === 5 && !serviceStarted"
type="primary"
@click="nextStep"
:loading="isProcessing"
:disabled="!canStartService"
>
{{ canStartService ? '启动服务' : '请先完成前置步骤' }}
</a-button>
<!-- 调试强制启动按钮 -->
<a-button
v-if="currentStep === 5 && !serviceStarted && !canStartService"
type="default"
@click="forceStartService"
:loading="isProcessing"
danger
>
强制启动调试用
</a-button>
<!-- 服务启动完成后的进入应用按钮 -->
<a-button
v-if="currentStep === 5 && serviceStarted"
type="primary" type="primary"
@click="enterApp" @click="enterApp"
> >
@@ -275,10 +298,10 @@ const dependenciesInstalled = ref(false)
// 镜像源配置 // 镜像源配置
const pythonMirrors = ref([ const pythonMirrors = ref([
{ key: 'official', name: 'Python 官方', url: 'https://www.python.org/ftp/python/3.13.0/', speed: null as number | null }, { key: 'official', name: 'Python 官方', url: 'https://www.python.org/ftp/python/3.12.0/', speed: null as number | null },
{ key: 'tsinghua', name: '清华 TUNA 镜像', url: 'https://mirrors.tuna.tsinghua.edu.cn/python/3.13.0/', speed: null as number | null }, { key: 'tsinghua', name: '清华 TUNA 镜像', url: 'https://mirrors.tuna.tsinghua.edu.cn/python/3.12.0/', speed: null as number | null },
{ key: 'ustc', name: '中科大镜像', url: 'https://mirrors.ustc.edu.cn/python/3.13.0/', speed: null as number | null }, // { key: 'ustc', name: '中科大镜像', url: 'https://mirrors.ustc.edu.cn/python/3.12.0/', speed: null as number | null },
{ key: 'huawei', name: '华为云镜像', url: 'https://mirrors.huaweicloud.com/repository/toolkit/python/3.13.0/', speed: null as number | null }, { key: 'huawei', name: '华为云镜像', url: 'https://mirrors.huaweicloud.com/repository/toolkit/python/3.12.0/', speed: null as number | null },
{ key: 'aliyun', name: '阿里云镜像', url: 'https://mirrors.aliyun.com/python-release/windows/', speed: null as number | null } { key: 'aliyun', name: '阿里云镜像', url: 'https://mirrors.aliyun.com/python-release/windows/', speed: null as number | null }
]) ])
@@ -287,7 +310,7 @@ const pipMirrors = ref([
{ key: 'tsinghua', name: '清华大学', url: 'https://pypi.tuna.tsinghua.edu.cn/simple/', speed: null as number | null }, { key: 'tsinghua', name: '清华大学', url: 'https://pypi.tuna.tsinghua.edu.cn/simple/', speed: null as number | null },
{ key: 'aliyun', name: '阿里云', url: 'https://mirrors.aliyun.com/pypi/simple/', speed: null as number | null }, { key: 'aliyun', name: '阿里云', url: 'https://mirrors.aliyun.com/pypi/simple/', speed: null as number | null },
{ key: 'douban', name: '豆瓣', url: 'https://pypi.douban.com/simple/', speed: null as number | null }, { key: 'douban', name: '豆瓣', url: 'https://pypi.douban.com/simple/', speed: null as number | null },
{ key: 'ustc', name: '中科大', url: 'https://pypi.mirrors.ustc.edu.cn/simple/', speed: null as number | null }, // { key: 'ustc', name: '中科大', url: 'https://pypi.mirrors.ustc.edu.cn/simple/', speed: null as number | null },
{ key: 'huawei', name: '华中科技大学', url: 'https://pypi.hustunique.com/simple/', speed: null as number | null } { key: 'huawei', name: '华中科技大学', url: 'https://pypi.hustunique.com/simple/', speed: null as number | null }
]) ])
@@ -311,18 +334,45 @@ const startingService = ref(false)
const showServiceProgress = ref(false) const showServiceProgress = ref(false)
const serviceProgress = ref(0) const serviceProgress = ref(0)
const serviceStatus = ref('准备启动后端服务...') const serviceStatus = ref('准备启动后端服务...')
const serviceStarted = ref(false) // 新增:服务是否已启动成功
// 全局进度条状态 // 全局进度条状态
const globalProgress = ref(0) const globalProgress = ref(0)
const globalProgressStatus = ref<'normal' | 'exception' | 'success'>('normal') const globalProgressStatus = ref<'normal' | 'exception' | 'success'>('normal')
const progressText = ref('') const progressText = ref('')
const allCompleted = computed(() => // 检查是否可以启动服务(前置条件都满足)
pythonInstalled.value && gitInstalled.value && backendExists.value && dependenciesInstalled.value const canStartService = computed(() => {
) const result = pythonInstalled.value && gitInstalled.value && backendExists.value && dependenciesInstalled.value
console.log('canStartService 计算结果:', {
pythonInstalled: pythonInstalled.value,
gitInstalled: gitInstalled.value,
backendExists: backendExists.value,
dependenciesInstalled: dependenciesInstalled.value,
result
})
return result
})
function jumpToLastStep() { // 检查是否全部完成(包括服务启动)
const allCompleted = computed(() => {
const result = pythonInstalled.value && gitInstalled.value && backendExists.value && dependenciesInstalled.value && serviceStarted.value
console.log('allCompleted 计算结果:', {
pythonInstalled: pythonInstalled.value,
gitInstalled: gitInstalled.value,
backendExists: backendExists.value,
dependenciesInstalled: dependenciesInstalled.value,
serviceStarted: serviceStarted.value,
result
})
return result
})
async function jumpToLastStep() {
console.log('跳转到第6步先检查环境状态')
currentStep.value = 5 currentStep.value = 5
// 跳转到第6步时重新检查环境状态
await checkEnvironment()
} }
function skipToHome(){ function skipToHome(){
router.push('/home') router.push('/home')
@@ -465,25 +515,30 @@ function prevStep() {
} }
async function nextStep() { async function nextStep() {
console.log('nextStep 被调用,当前步骤:', currentStep.value)
isProcessing.value = true isProcessing.value = true
errorMessage.value = '' errorMessage.value = ''
try { try {
switch (currentStep.value) { switch (currentStep.value) {
case 0: // 主题设置 case 0: // 主题设置
console.log('执行主题设置')
saveSettings() saveSettings()
break break
case 1: // Python 环境 case 1: // Python 环境
console.log('执行Python环境安装')
if (!pythonInstalled.value) { if (!pythonInstalled.value) {
await installPython() await installPython()
} }
break break
case 2: // Git 工具 case 2: // Git 工具
console.log('执行Git工具安装')
if (!gitInstalled.value) { if (!gitInstalled.value) {
await installGit() await installGit()
} }
break break
case 3: // 源码获取 case 3: // 源码获取
console.log('执行源码获取')
if (!backendExists.value) { if (!backendExists.value) {
await cloneBackend() await cloneBackend()
} else { } else {
@@ -491,11 +546,13 @@ async function nextStep() {
} }
break break
case 4: // 依赖安装 case 4: // 依赖安装
console.log('执行依赖安装')
if (!dependenciesInstalled.value) { if (!dependenciesInstalled.value) {
await installDependencies() await installDependencies()
} }
break break
case 5: // 启动服务 case 5: // 启动服务
console.log('执行启动服务')
await startBackendService() await startBackendService()
break break
} }
@@ -506,6 +563,7 @@ async function nextStep() {
await autoStartSpeedTest() await autoStartSpeedTest()
} }
} catch (error) { } catch (error) {
console.error('nextStep 执行出错:', error)
errorMessage.value = error instanceof Error ? error.message : String(error) errorMessage.value = error instanceof Error ? error.message : String(error)
stepStatus.value = 'error' stepStatus.value = 'error'
} finally { } finally {
@@ -551,21 +609,28 @@ async function checkEnvironment() {
const status = await window.electronAPI.checkEnvironment() const status = await window.electronAPI.checkEnvironment()
logger.info('环境检查结果', status) logger.info('环境检查结果', status)
console.log('环境检查结果:', status)
pythonInstalled.value = status.pythonExists pythonInstalled.value = status.pythonExists
gitInstalled.value = status.gitExists gitInstalled.value = status.gitExists
backendExists.value = status.backendExists backendExists.value = status.backendExists
dependenciesInstalled.value = status.dependenciesInstalled dependenciesInstalled.value = status.dependenciesInstalled
// 如果所有环境都已准备好,跳到最后一步 // 如果所有环境都已准备好,跳到最后一步,但不自动启动服务
if (status.isInitialized) { if (status.isInitialized) {
logger.info('环境已初始化完成,跳转到启动服务步骤') logger.info('环境已初始化完成,跳转到启动服务步骤(但不自动启动)')
console.log('环境已初始化完成跳转到第6步')
currentStep.value = 5 currentStep.value = 5
await startBackendService() // 移除自动启动服务的逻辑,让用户手动点击启动
// await startBackendService()
} else {
logger.info('环境未完全初始化,停留在初始化页面')
console.log('环境未完全初始化,当前步骤:', currentStep.value)
} }
} catch (error) { } catch (error) {
const errorMsg = `环境检查失败: ${error instanceof Error ? error.message : String(error)}` const errorMsg = `环境检查失败: ${error instanceof Error ? error.message : String(error)}`
logger.error('环境检查失败', error) logger.error('环境检查失败', error)
console.error('环境检查失败:', error)
errorMessage.value = errorMsg errorMessage.value = errorMsg
} }
} }
@@ -648,6 +713,7 @@ async function startBackendService() {
if (result.success) { if (result.success) {
serviceProgress.value = 100 serviceProgress.value = 100
serviceStatus.value = '后端服务启动成功' serviceStatus.value = '后端服务启动成功'
serviceStarted.value = true // 设置服务启动成功状态
stepStatus.value = 'finish' stepStatus.value = 'finish'
logger.info('后端服务启动成功') logger.info('后端服务启动成功')
} else { } else {
@@ -656,6 +722,7 @@ async function startBackendService() {
} }
} catch (error) { } catch (error) {
serviceStatus.value = '后端服务启动失败' serviceStatus.value = '后端服务启动失败'
serviceStarted.value = false // 确保启动失败时状态正确
logger.error('后端服务启动异常', error) logger.error('后端服务启动异常', error)
throw error throw error
} finally { } finally {
@@ -663,8 +730,17 @@ async function startBackendService() {
} }
} }
// 强制启动服务(调试用)
async function forceStartService() {
console.log('强制启动服务(忽略前置条件检查)')
await startBackendService()
}
// 进入应用 // 进入应用
function enterApp() { function enterApp() {
// 设置初始化完成标记
localStorage.setItem('app-initialized', 'true')
console.log('设置初始化完成标记,跳转到首页')
router.push('/home') router.push('/home')
} }
@@ -699,12 +775,20 @@ function handleDownloadProgress(progress: DownloadProgress) {
} }
onMounted(async () => { onMounted(async () => {
console.log('初始化页面 onMounted 开始')
loadSettings() loadSettings()
// 添加延迟,确保页面完全加载后再检查环境
setTimeout(async () => {
console.log('开始环境检查')
await checkEnvironment() await checkEnvironment()
window.electronAPI.onDownloadProgress(handleDownloadProgress)
// 如果当前步骤需要测速,自动开始测速 // 如果当前步骤需要测速,自动开始测速
await autoStartSpeedTest() await autoStartSpeedTest()
}, 100)
window.electronAPI.onDownloadProgress(handleDownloadProgress)
console.log('初始化页面 onMounted 完成')
}) })
onUnmounted(() => { onUnmounted(() => {