[英]How to pass a data array from express.js to ejs template and render them
[英]Pass array from python to external express.js
在后端,我有一個 python 程序(vmstats.py),它將字符串數據存儲在 vmonoff[] 中:
vmstats.py
import json
from proxys import ProxyServer
vmonoff = []
proxys = ProxyServer('XXXXXX','UUUUUU','PPPPPP')
for b in proxys.listeners:
if "MYVMNAME" in b.vname:
if b.stat=="UP":
vmonoff.append('./images/vm_on.png')
else:
vmonoff.append('./images/vm_off.png')
print('{:<10}'.format(b.vname), '{:<8}'.format('Status:'), '{:>6}'.format(b.stat))
response = json.dumps(vmonoff)
exec.controller.js
const {exec} = require('child_process');
const path = require('path');
const fs = require('fs');
const htmlFile = path.join(__dirname, '/index.html');
exports.executeReport = (req, res) => {
execute("python3 ./src/vmstats.py", res);
}
var responseObject = JSON.parse(response);
const execute = (command, res) => {
exec(command, (error, stdout, stderr) => {
if (error) {
res.send({result: `error: ${error.message}`});
return;
}
if (stderr) {
res.send({result: `stderr: ${stderr}`});
return;
}
createHtmlFile(stdout);
res.sendFile(htmlFile);
return;
});
}
const createHtmlFile = (stdout) => {
const rows = stdout.split('\n');
const content = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div class="container">
<div style="text-align: center">
<h3>TEST</h3>
<br>
</div>
</div>
</body>
</html>`
fs.writeFileSync(htmlFile, content);
}
在前端(exec.controller.js),我嘗試使用:
var responseObject = JSON.parse(響應)
但我得到了ReferenceError: response is not defined
如何將vmonoff[]
從 python 轉移到外部 express.js?
首先,您的 python 腳本似乎對stdout
沒有 output 任何內容(通常使用類似print
的內容完成),因此,Node JS 沒有什么可從那里讀取的。
除了createHtmlFile
中的rows
變量之外,沒有在任何地方使用。
在 python 腳本中,您需要打印數組:
response = json.dumps(vmonoff)
print(response)
在節點腳本中, stdout
是你獲取數據的地方,你可以在那里解析它並進一步處理它:
const execute = (command, res) => {
exec(command, (error, stdout, stderr) => {
if (error) {
res.send({result: `error: ${error.message}`});
return;
}
if (stderr) {
res.send({result: `stderr: ${stderr}`});
return;
}
var responseObject = JSON.parse(stdout);
createHtmlFile(responseObject);
res.sendFile(htmlFile);
return;
});
}
然后在createHtmlFile
中,您可以構造 HTML (例如,迭代數組元素,或者可能使用.join
而不是.split
,尚不清楚 HTML 應該是什么樣子......)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.