前面铺垫了这么多,这一节就要真正的实现Electron与python联合编程。这一节我通过加法器这个简单的例子来演示如何真正实现Electron和Flask联合编程。
在终端工具选项卡中输入如下命令安装Axios
包:
npm i --save-dev axios
项目结构如下图所示,python
目录下的sum.py
作为后端实现一个最基本的加法运算;server
目录下的server.py
作为Flask
服务器。
软件界面包括两个输入框、一个按钮还有一个输出框,输入框用来输入两个需要相加的数字,点击按钮后在按钮右边的输出框中会显示两个数字相加之和,代码如下:
简单加法演示
请输入第一个数字:
请输入第二个数字:
界面如下:
预加载函数暴露两个api函数,electronAPI.summation
以及electronAPI.summation_response
,前者用于计算两个数字之和,后者用于将相加结果输出到界面的输出框中。
const { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('electronAPI',{summation: (options) => ipcRenderer.invoke('summation', options),summation_response: (callback) => ipcRenderer.on('summation-response', callback)})
渲染函数通过预加载函数中的api实现所需功能。
document.getElementById('btn_sum').addEventListener('click',async ()=>{let num_a = document.getElementById('num_a').value;let num_b = document.getElementById('num_b').value;let options = {method:'post',url:'http://127.0.0.1:5000/summation',//headers:{'Content-Type': 'application/json'},data:{numa:num_a,numb:num_b}}await window.electronAPI.summation(options)
})
window.electronAPI.summation_response((event, result) => {document.getElementById('summation').value = result
})
const {app, BrowserWindow, ipcMain} = require('electron');
const path = require('path');
const axios = require('axios'); //request请求库
let win = null;function createWindow () {win = new BrowserWindow({webPreferences: {preload: path.join(__dirname, 'preload.js'),}});win.loadFile('html/index.html').then(()=>{});
}
app.whenReady().then(() => {ipcMain.handle('summation', async (event,options)=>{await axios(options).then(function (response) {win.webContents.send('summation-response', response.data.result)}).catch(function (error) {console.log(error);})})createWindow();app.on('activate', function () {if (BrowserWindow.getAllWindows().length === 0) createWindow();});
});app.on('window-all-closed', function () {if (process.platform !== 'darwin') app.quit();
})
路由函数调用sum.py后端函数实现相加功能,并将result作为response返回给
from flask import Flask, request
from python.sum import addapp = Flask(__name__)@app.route("/summation", methods=['POST'])
def summation():numa = int(request.json.get('numa'))numb = int(request.json.get('numb'))result = add(numa, numb)return resultif __name__ == '__main__':app.run(host='127.0.0.1', port=5000, debug=True)
def add(num_a, num_b):result = num_a + num_breturn {'result': result}