[英]How can I wait a Python shell to execute before serving file
I've an express server route which receives a xml file, then parses and return it as json.我有一个快速服务器路由,它接收 xml 文件,然后将其解析并返回为 json。
When a user sends a file, it saves in a directory './upload', parses it with a Python script then output json in './json-output', which is served.当用户发送文件时,它保存在目录“./upload”中,使用 Python 脚本解析它,然后在 output json 中提供服务。
When I first upload a file, the response comes empty.当我第一次上传文件时,响应为空。 But when I do the same upload steps (there is a json already created from last upload on './json-output' dir), it serves the json.
但是,当我执行相同的上传步骤时(从上次上传到 './json-output' 目录中已经创建了一个 json),它服务于 json。 It seems some asynchronous issue but I couldn't fix it.
这似乎是一些异步问题,但我无法修复它。
app.post('/upload', function(req, res) {
upload(req, res, async function(err) {
if (err) {
res.json({ error_code: 1, err_desc: err });
return;
}
if (!req.file) {
res.json({ error_code: 1, err_desc: 'No file passed' });
return;
}
let fileName = req.file.originalname;
const options = {
args: [ fileName ]
};
const parserPath = path.join(__dirname + '/parser/parser.py');
const readFile = promisify(PythonShell.run);
await readFile(parserPath, options);
fileName = fileName.split('.')[0];
res.sendFile(path.join(__dirname + `/json-output/${fileName}.json`));
});
});
I'm running it inside a docker images我在 docker 图像中运行它
This a quite a "Dirty fix" in my eyes but you could do a while loop EG:在我看来,这是一个相当“肮脏的修复”,但你可以做一个 while 循环 EG:
fileName = fileName.split('.')[0];
while (!fs.existsSync(path.join(__dirname + `/json-output/${fileName}.json`)){
console.log('File does not exist!')
}
//Becareful you should delete the file once the res.send is done
res.sendFile(path.join(__dirname + `/json-output/${fileName}.json`));
Decided to read the python-shell docs here an idea: https://www.npmjs.com/package/python-shell#exchanging-data-between-node-and-python决定在这里阅读python-shell文档一个想法: https://www.npmjs.com/package/python-shell#exchanging-data-between-node-and-python
So, in theory, you can start a new所以,理论上,你可以开始一个新的
let pyshell = new PythonShell(path.join(__dirname + '/parser/parser.py'),options);
pyshell.end(function (err,code,signal) {
if (err) throw err;
fileName = fileName.split('.')[0];
res.sendFile(path.join(__dirname + `/json-output/${fileName}.json`));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.