99偷拍视频精品区一区二,口述久久久久久久久久久久,国产精品夫妇激情啪发布,成人永久免费网站在线观看,国产精品高清免费在线,青青草在线观看视频观看,久久久久久国产一区,天天婷婷久久18禁,日韩动漫av在线播放直播

Python + Vue Electron 構(gòu)建桌面應(yīng)用

前言

通過(guò)Electron技術(shù) + python 構(gòu)建桌面應(yīng)用實(shí)際上非常麻煩,需要使用python構(gòu)成后端并打包,然后使用Vue作為前端,還要用Electron打包。
但是好處就是可以同時(shí)得到來(lái)自前端UI框架的高顏值支持以及python海量輪子的快速實(shí)現(xiàn)(以及較為完善的多端部署功能),項(xiàng)目可以快速擴(kuò)展成全平臺(tái)應(yīng)用。
所以我在這個(gè)博客里記錄了Python + Vue Electron 構(gòu)建桌面應(yīng)用的方法。
(其實(shí)單純使用node.js進(jìn)行開(kāi)發(fā)可能會(huì)更快,畢竟不用寫后端api,但是python的社區(qū)有很多超級(jí)方便的庫(kù),可以節(jié)約大量的時(shí)間,比較起來(lái)還是寫api來(lái)得節(jié)省時(shí)間)

成都創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),雙峰企業(yè)網(wǎng)站建設(shè),雙峰品牌網(wǎng)站建設(shè),網(wǎng)站定制,雙峰網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷,網(wǎng)絡(luò)優(yōu)化,雙峰網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。

Step 1. 新建Vue項(xiàng)目

vue create vue-electron-app

Step 2. 選擇一個(gè)UI框架

Naive UI

npm i -D naive-ui
npm i -D vfonts

為了方便,全局引入U(xiǎn)I組件,在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中多了幾個(gè)命令

運(yùn)行npm run electron:serve

到這里就基本完成前端部分的環(huán)境設(shè)置,后續(xù)只需要像開(kāi)發(fā)web應(yīng)用一樣寫api就行了

Step 4. 創(chuàng)建后端項(xiàng)目,作者使用FastAPI作為Python后端框架

安裝fastapi及其依賴項(xiàng)
pip install fastapi[all] pyinstaller

一部分Python代碼,用于測(cè)試
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 不能省略,否則服務(wù)器無(wú)法啟動(dòng)。

Step 5. 配置前后端聯(lián)合啟動(dòng)

因?yàn)槭亲烂娑塑浖谇岸薊lectron打包,后端pyinstaller打包之后,需要在啟動(dòng)前端的Electron .exe文件時(shí),也同時(shí)啟動(dòng)pyinstaller打包的后端exe文件,這就需要在前端代碼中寫入命令行以喚起后端的exe,并在退出時(shí)關(guān)閉后端exe。
首先安裝node-cmd,yarn add node-cmd
然后在管理electron生命周期的項(xiàng)目名.js 文件中,完成以下代碼以喚起和關(guān)閉后端exe

點(diǎn)擊查看代碼
'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`)
  // 啟動(dòng)服務(wù)器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()
        // 關(guān)閉服務(wù)器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
這里項(xiàng)目中使用的后端端口是5003,但是在實(shí)際生產(chǎn)環(huán)境中端口有可能被占用,所以有必要在開(kāi)發(fā)時(shí)將后端最終運(yùn)行的端口號(hào)記錄在數(shù)據(jù)庫(kù)里

最終達(dá)到的效果就是啟動(dòng)前端exe時(shí),后端進(jìn)程同時(shí)打開(kāi),關(guān)閉前端exe時(shí),后端exe也同時(shí)關(guān)閉

Step 6. 配置跨域CORS

由于瀏覽器默認(rèn)禁止跨域通信,為了讓工作在不同端口上的服務(wù)可以互相通信,需要配置CORS,最簡(jiǎn)單的辦法就是禁用掉CORS,
參考:https://pratikpc.medium.com/bypassing-cors-with-electron-ab7eaf

項(xiàng)目名.js 文件中寫入以下代碼:

點(diǎn)擊查看代碼
const win = new BrowserWindow({
    webPreferences: {
        webSecurity: false
    }
});
現(xiàn)在就可以通過(guò)api通信讓前端js調(diào)用后端的python api了。

到目前為止,一個(gè)前后端全棧的Electron桌面應(yīng)用的功能就已經(jīng)基本實(shí)現(xiàn)了。

分享題目:Python + Vue Electron 構(gòu)建桌面應(yīng)用
網(wǎng)站鏈接:http://www.yijiale78.com/article46/dsoggeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航面包屑導(dǎo)航網(wǎng)站建設(shè)網(wǎng)站排名網(wǎng)站內(nèi)鏈服務(wù)器托管

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司