通過Electron技術 + python 構建桌面應用實際上非常麻煩,需要使用python構成后端并打包,然后使用Vue作為前端,還要用Electron打包。
但是好處就是可以同時得到來自前端UI框架的高顏值支持以及python海量輪子的快速實現(以及較為完善的多端部署功能),項目可以快速擴展成全平臺應用。
所以我在這個博客里記錄了Python + Vue Electron 構建桌面應用的方法。
(其實單純使用node.js進行開發可能會更快,畢竟不用寫后端api,但是python的社區有很多超級方便的庫,可以節約大量的時間,比較起來還是寫api來得節省時間)
成都創新互聯公司是一家集網站建設,雙峰企業網站建設,雙峰品牌網站建設,網站定制,雙峰網站建設報價,網絡營銷,網絡優化,雙峰網站推廣為一體的創新建站企業,幫助傳統企業提升企業形象加強企業競爭力。可充分滿足這一群體相比中小企業更為豐富、高端、多元的互聯網需求。同時我們時刻保持專業、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們為更多的企業打造出實用型網站。
vue create vue-electron-app
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')
vue add electron-builder
安裝成功后package.json中多了幾個命令
運行npm run electron:serve
到這里就基本完成前端部分的環境設置,后續只需要像開發web應用一樣寫api就行了
安裝fastapi及其依賴項
pip install fastapi[all] pyinstaller
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
不能省略,否則服務器無法啟動。
因為是桌面端軟件,在前端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 === '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也同時關閉
由于瀏覽器默認禁止跨域通信,為了讓工作在不同端口上的服務可以互相通信,需要配置CORS,最簡單的辦法就是禁用掉CORS,
參考:https://pratikpc.medium.com/bypassing-cors-with-electron-ab7eaf
在 項目名.js
文件中寫入以下代碼:
const win = new BrowserWindow({
webPreferences: {
webSecurity: false
}
});
到目前為止,一個前后端全棧的Electron桌面應用的功能就已經基本實現了。
分享題目:Python + Vue Electron 構建桌面應用
網站鏈接:http://m.kartarina.com/article46/dsoggeg.html
成都網站建設公司_創新互聯,為您提供網站導航、面包屑導航、網站建設、網站排名、網站內鏈、服務器托管
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯