您可以创建一个 Express 服务器,其端点调用您的 NLP 后端(用 Python 编写)并检索其输出。
如何实现
一些假设
在这里,我假设您打算将用户的输入文本从您的 NodeJS 服务器发送到您的 Python NLP 后端进行翻译并作为有效响应发送回您的 NodeJS 服务器。
计划
假设您的 Express 服务器上有一个名为 http://localhost:3000/Morrocan_NLP?text=mytexttotranslate 的端点。我们将把查询参数text = "mytexttotranslate" 提供给一个Python 脚本,该脚本将在/Morrocan_NLP 端点接收它。然后,此 Python 脚本将处理该文本并将其发送回您的 NodeJS Express 服务器。
为此,您可以在 NodeJS Express 应用程序中设置有效路由,并使用子进程从中调用相关的 Python 脚本以下是展示此交互的假设代码示例: p>
// Setting up your Express server
const express = require('express');
const app = express();
// Step 1:
// Set up the /Morrocan_NLP Express route
app.get('/Morrocan_NLP', invokePythonMorrocanTranslator);
// Step 2:
// Create a callback function that handles requests to the '/Morrocan_NLP' endpoint
function invokePythonMorrocanTranslator(req, res) {
// Importing Node's 'child_process' module to spin up a child process.
// There are other ways to create a child process but we'll use the
// simple spawn function here.
var spawn = require("child_process").spawn;
// The spawned python process which takes 2 arguments, the name of the
// python script to invoke and the query parameter text = "mytexttotranslate"
var process = spawn('python',
[
"./morrocan_nlp.py"
req.query.text
]
);
// Step 3:
// Listen for data output from stdout, in this case, from "morrocan_nlp.py"
process.stdout.on('data', function(data) {
// Sends the output from "morrocan_nlp.py" back to the user
res.send(data.toString());
});
}
在您的名为morrocan_nlp.py 的进行摩洛哥翻译的 Python 脚本(只是一个假设的脚本)中,您将拥有类似的东西来接收和处理 NodeJS 服务器的查询并将结果返回给它。
import sys
# This is how you'll receive the queries from your NodeJS server
# Notice that sys.argv[1] refers to the 2nd argument of the list passed
# into the spawn('python', ...) function in your NodeJS server code above
text_from_node_server = str(sys.argv[1])
# perform_translation here is a function I made up that
# translates any text into Morrocan
translated_text = perform_translation(text_from_node_server)
# return your processed text to the NodeJS server via stdout
print(translated_text)
sys.stdout.flush()
外部资源
这是 NodeJS 服务器之间通信的基本方式 Python 脚本,但是,如果您正在构建大型应用程序,这可能不是最具可扩展性和最有效的方式。因此,我建议您参考this article,其中包含有关如何以其他更可靠的方式集成 NodeJS 和 Python 的分步教程。我真的希望这对您或任何其他阅读本文的人有所帮助!