前言
通過Electron技術 + python 構建桌面應用實際上非常麻煩,需要使用python構成后端并打包,然后使用Vue作為前端,還要用Electron打包,
但是好處就是可以同時得到來自前端UI框架的高顏值支持以及python海量輪子的快速實作(以及較為完善的多端部署功能),專案可以快速擴展成全平臺應用,
所以我在這個博客里記錄了Python + Vue Electron 構建桌面應用的方法,
(其實單純使用node.js進行開發可能會更快,畢竟不用寫后端api,但是python的社區有很多超級方便的庫,可以節約大量的時間,比較起來還是寫api來得節省時間)
Step 1. 新建Vue專案
vue create vue-electron-app
Step 2. 選擇一個UI框架
Naive UI
npm i -D naive-ui
npm i -D vfonts
為了方便,全域引入UI組件,在main.js 中添加
import naive from 'naive-ui'
createApp(App).use(naive).use(store).use(router).mount('#app')
Step 3. 安裝 electron-builder
vue add electron-builder
安裝成功后package.json中多了幾個命令

運行npm run electron:serve

到這里就基本完成前端部分的環境設定,后續只需要像開發web應用一樣寫api就行了
Step 4. 創建后端專案,作者使用FastAPI作為Python后端框架
安裝fastapi及其依賴項
pip install fastapi[all] pyinstaller
一部分Python代碼,用于測驗
from fastapi import FastAPI
import uvicorn
# 組態檔
from config import This_config
import logging
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == '__main__':
logging.basicConfig(filename='log.log', encoding='utf-8', level=logging.INFO, format='%(asctime)s %(message)s')
logging.info("Now start service")
try:
uvicorn.run("main:app", host="localhost", port=This_config['port'], log_level="info")
except Exception as e:
logging.error(e)
下面的命令用于pyinstaller打包
pyinstaller --uac-admin -w main.py --distpath W:\YoutubeProject\frontend\vue-electron-app\dist_electron\win-unpacked\backend_dist --hidden-import=main
需要注意的是,--hidden-import=main 不能省略,否則服務器無法啟動,
Step 5. 配置前后端聯合啟動
因為是桌面端軟體,在前端Electron打包,后端pyinstaller打包之后,需要在啟動前端的Electron .exe檔案時,也同時啟動pyinstaller打包的后端exe檔案,這就需要在前端代碼中寫入命令列以喚起后端的exe,并在退出時關閉后端exe,
首先安裝node-cmd,yarn add node-cmd
然后在管理electron生命周期的專案名.js 檔案中,完成以下代碼以喚起和關閉后端exe
點擊查看代碼
'use strict'
import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
var cmd=require('node-cmd');
// 獲取程式的根目錄地址
var currentPath = require("path").dirname(require('electron').app.getPath("exe"));
const isDevelopment = process.env.NODE_ENV !== 'production'
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
async function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
cmd.run(`taskkill /F /im main.exe`)
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS3_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
console.log("now start service")
console.log(`${currentPath}/backend_dist/main/main.exe`)
// 啟動服務器exe
cmd.run(`${currentPath}/backend_dist/main/main.exe`,function(err, data, stderr){
console.log(data)
console.log(err)
console.log(stderr)
});
createWindow()
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', (data) => {
if (data =https://www.cnblogs.com/SongLink/p/=='graceful-exit') {
app.quit()
// 關閉服務器exe
cmd.run(`taskkill /F /im main.exe`)
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
cmd.run(`taskkill /F /im main.exe`)
})
}
}
需要注意的是后端pyinstaller打包的程式需要安裝到指定的目錄中:${currentPath}/backend_dist/main/main.exe
這里專案中使用的后端埠是5003,但是在實際生產環境中埠有可能被占用,所以有必要在開發時將后端最終運行的埠號記錄在資料庫里
最終達到的效果就是啟動前端exe時,后端行程同時打開,關閉前端exe時,后端exe也同時關閉

Step 6. 配置跨域CORS
由于瀏覽器默認禁止跨域通信,為了讓作業在不同埠上的服務可以互相通信,需要配置CORS,最簡單的辦法就是禁用掉CORS,
參考:https://pratikpc.medium.com/bypassing-cors-with-electron-ab7eaf331605
在 專案名.js 檔案中寫入以下代碼:
點擊查看代碼
const win = new BrowserWindow({
webPreferences: {
webSecurity: false
}
});
到目前為止,一個前后端全堆疊的Electron桌面應用的功能就已經基本實作了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/499317.html
標籤:Python
