簡體   English   中英

節點如何在使用 pug 和 express 節點網站單擊按鈕時運行 python 腳本

[英]Node how to run python script when clicking button using pug and express node website

我正在嘗試使用我在 pug 中創建的網頁運行 python 腳本,在 node.js 中表達。 我對python比node更熟悉。 使用下面如何運行python腳本? 我包含了 python shell,但不確定當我單擊 pug 網頁上的按鈕時如何運行 python 腳本。

服務器.js

// require all dependencies
var express = require('express');
var app = express();
var PythonShell = require('python-shell');


// set up the template engine
app.set('views', './views');
app.set('view engine', 'pug');

var options = {
  mode: 'text',
  pythonOptions: ['-u'],
  scriptPath: '../hello.py',
  args: ['value1', 'value2', 'value3']
};



// GET response for '/'
app.get('/', function (req, res) {

    // render the 'index' template, and pass in a few variables
    res.render('index', { title: 'Hey', message: 'Hello' });

PythonShell.run('hello.py', options, function (err, results) {
    if (err) throw err;
    // results is an array consisting of messages collected during execution
    console.log('results: %j', results);
});

});

// start up the server
app.listen(3000, function () {
    console.log('Listening on http://localhost:3000');
});

索引.pug

html
    head
        title= title
    body
        h1= message
        a(href="http://www.google.com"): button(type="button") Run python script

創建另一條路線,您將在單擊按鈕時調用該路線。 我們稱之為/foo 現在為此路由設置處理程序:

const { spawn } = require('child_process')
app.get('/foo', function(req, res) {
    // Call your python script here.
    // I prefer using spawn from the child process module instead of the Python shell
    const scriptPath = 'hello.py'
    const process = spawn('python', [scriptPath, arg1, arg2])
    process.stdout.on('data', (myData) => {
        // Do whatever you want with the returned data.
        // ...
        res.send("Done!")
    })
    process.stderr.on('data', (myErr) => {
        // If anything gets written to stderr, it'll be in the myErr variable
    })
})

現在在前端使用 pug 創建按鈕。 在您的客戶端 javascript 中,單擊此按鈕時對/foo進行 AJAX 調用。 例如,

button(type="button", onclick="makeCallToFoo()") Run python script

在您的客戶端 JS 中:

function makeCallToFoo() {
    fetch('/foo').then(function(response) {
        // Use the response sent here
    })
}

編輯:您還可以以類似的方式使用您已經在使用的 shell 模塊。 如果您不想要客戶端 JS,您可以將按鈕封裝在一個帶有屬性的表單中: method="get" action="/foo" 例如,

form(method="get" action="/foo")
    button(type="submit") Run python script

讓我們來看看。 通常,我為了與 python/nodejs 交互,我使用 djangorestframework,它使用服務器方法 GET、POST 等。所以首先你必須在 python 中有一個正在運行的服務器和腳本。 然后在節點中,您可以使用 jquery 或 js 框架來偵聽節點應用程序中的事件。 單擊按鈕時,將向 python 發送獲取/發布請求。 在 python 中,您還可以使用 javascript 對腳本進行條件渲染,例如:if request == POST: //run script。 由於腳本是從節點運行的,因此您必須在單擊按鈕時通過節點中的 http 觸發事件。 只是一個想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM