如何在Python和 Node.js 之间传递 JSON 数据?
以下文章介绍了如何在Python和 Node.js 之间通信 JSON 数据。假设我们正在使用 Node.js 应用程序,并且我们想要使用一个仅在Python可用的特定库,反之亦然。我们应该能够将结果从一种语言共享到另一种语言并实现它,我们将使用 JSON,因为它与语言无关。
方法:
- 为每种语言设置一个服务器,并使用旧的 GET 和 POST 请求使用 JSON 共享数据。
- 从 Node.js 调用Python后台进程,反之亦然,并在两个实例中监听进程的stdout流。
项目结构:下面使用的所有文件都位于相同的目录中,如下所示。
1. 使用服务器:这类似于使用第三方 API 服务的方法,其中我们向远程服务器发出 GET 请求以获取数据,并发出 POST 请求以发送数据。唯一的区别是我们将在本地运行服务器(这也适用于具有所需 URL 的远程服务器)。
Node.js 到Python:当我们在 node.js 中工作并且想要在Python处理一些数据时。
在下面的示例中,我们将为Python设置一个服务器并从 node.js 发出请求。我们使用Flask微框架,因为这是在Python设置服务器并在 Node.js 中发出请求的最简单方法,我们需要一个请求包。
模块安装:
- 使用以下命令为Python安装 Flask 模块:
pip install flask
- 使用以下命令为 NodeJS 安装请求模块:
npm install request-promise
示例:计算包含整数的数组的总和并将结果返回给 Node.js
pyserver.py
from flask import Flask
import json
# Setup flask server
app = Flask(__name__)
# Setup url route which will calculate
# total sum of array.
@app.route('/arraysum', methods = ['POST'])
def sum_of_array():
data = request.get_json()
print(data)
# Data variable contains the
# data from the node server
ls = data['array']
result = sum(ls) # calculate the sum
# Return data in json format
return json.dumps({"result":result})
if __name__ == "__main__":
app.run(port=5000)
talk.js
var request = require('request-promise');
async function arraysum() {
// This variable contains the data
// you want to send
var data = {
array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
var options = {
method: 'POST',
// http:flaskserverurl:port/route
uri: 'http://127.0.0.1:5000/arraysum',
body: data,
// Automatically stringifies
// the body to JSON
json: true
};
var sendrequest = await request(options)
// The parsedBody contains the data
// sent back from the Flask server
.then(function (parsedBody) {
console.log(parsedBody);
// You can do something with
// returned data
let result;
result = parsedBody['result'];
console.log("Sum of Array from Python: ", result);
})
.catch(function (err) {
console.log(err);
});
}
arraysum();
nodeserver.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post("/arraysum", (req, res) => {
// Retrieve array form post body
var array = req.body.array;
console.log(array);
// Calculate sum
var sum = 0;
for (var i = 0; i < array.length; i++) {
if (isNaN(array[i])) {
continue;
}
sum += array[i];
}
console.log(sum);
// Return json response
res.json({ result: sum });
});
// Server listening to PORT 3000
app.listen(3000);
talk.py
import requests
# Sample array
array = [1,2,3,4,5,6,7,8,9,10]
# Data that we will send in post request.
data = {'array':array}
# The POST request to our node server
res = requests.post('http://127.0.0.1:3000/arraysum', json=data)
# Convert response data to json
returned_data = res.json()
print(returned_data)
result = returned_data['result']
print("Sum of Array from Node.js:", result)
arraysum.py
import sys, json
# Function to calculate the sum of array
def arraysum(arr):
return sum(arr)
# Get the command line arguments
# and parse it to json
data = json.loads(sys.argv[1])
# Get the required field from
# the data
array = data['array']
# Calculate the result
result = arraysum(array)
# Print the data in stringified
# json format so that we can
# easily parse it in Node.js
newdata = {'sum':result}
print(json.dumps(newdata))
caller.js
const spawn = require('child_process').spawn;
// Initialise the data
const data = {
array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
// We need to stringify the data as
// python cannot directly read JSON
// as command line argument.
let stringifiedData = JSON.stringify(data);
// Call the python process and pass the
// data as command line argument.
const py = spawn('python', ['arraysum.py', stringifiedData]);
resultString = '';
// As the stdout data stream is chunked,
// we need to concat all the chunks.
py.stdout.on('data', function (stdData) {
resultString += stdData.toString();
});
py.stdout.on('end', function () {
// Parse the string as JSON when stdout
// data stream ends
let resultData = JSON.parse(resultString);
let sum = resultData['sum'];
console.log('Sum of array from Python process =', sum);
});
arraysum.js
// Function to calculate sum of array
function arraysum(arr) {
let sum = 0;
for (var i = 0; i < arr.length; i++) {
if (isNaN(arr[i])) {
continue;
}
sum += arr[i];
}
return sum;
}
// Get the command line arguments and
// parse it to json
var data = JSON.parse(process.argv[2]);
// Get the required field form the data.
array = data['array'];
// Calculate the result.
var sum = arraysum(array);
// Print the data in stringified json
// format so that we can easily parse
// it in Python
const newData = { sum }
console.log(JSON.stringify(newData));
Python3
from subprocess import Popen, PIPE
import json
# Initialise the data
array = [1,2,3,4,5,6,7,8,9,10]
data = {'array':array}
# Stringify the data.
stingified_data = json.dumps(data)
# Call the node process and pass the
# data as command line argument
process = Popen(['node', 'arraysum.js',
stingified_data], stdout=PIPE)
# This line essentially waits for the
# node process to complete and then
# read stdout data
stdout = process.communicate()[0]
# The stdout is a bytes string, you can
# convert it to another encoding but
# json.loads() supports bytes string
# so we aren't converting
# Parse the data into json
result_data = json.loads(stdout)
array_sum = result_data['sum']
print('Sum of array from Node.js process =',array_sum)
使用以下命令运行服务器。
python pyserver.py
这将在http://127.0.0.1:5000/启动服务器。现在我们从 Node.js 向http://127.0.0.1:5000/arraysum发出一个 POST 请求
谈话.js
var request = require('request-promise');
async function arraysum() {
// This variable contains the data
// you want to send
var data = {
array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
var options = {
method: 'POST',
// http:flaskserverurl:port/route
uri: 'http://127.0.0.1:5000/arraysum',
body: data,
// Automatically stringifies
// the body to JSON
json: true
};
var sendrequest = await request(options)
// The parsedBody contains the data
// sent back from the Flask server
.then(function (parsedBody) {
console.log(parsedBody);
// You can do something with
// returned data
let result;
result = parsedBody['result'];
console.log("Sum of Array from Python: ", result);
})
.catch(function (err) {
console.log(err);
});
}
arraysum();
通过以下命令运行此脚本。
node talk.js
输出:
{ result: 55 }
Sum of Array from Python: 55
Python到 Node.js:当我们在Python中工作并且想要在 Node.js 中处理一些数据时。
在这里,我们将反转上述过程,并使用express在 node.js 中启动服务器并在Python请求包。
模块安装:
- 使用以下命令为Python安装请求模块:
pip install requests
- 使用以下命令为 NodeJS 安装 express 和 body-parser 模块:
npm install express npm install body-parser
节点服务器.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post("/arraysum", (req, res) => {
// Retrieve array form post body
var array = req.body.array;
console.log(array);
// Calculate sum
var sum = 0;
for (var i = 0; i < array.length; i++) {
if (isNaN(array[i])) {
continue;
}
sum += array[i];
}
console.log(sum);
// Return json response
res.json({ result: sum });
});
// Server listening to PORT 3000
app.listen(3000);
使用以下命令运行服务器。
node nodeserver.js
这会在http://127.0.0.1:3000/启动服务器。现在我们从Python向127.0.0.1:3000/arraysum发出 POST 请求
谈话.py
import requests
# Sample array
array = [1,2,3,4,5,6,7,8,9,10]
# Data that we will send in post request.
data = {'array':array}
# The POST request to our node server
res = requests.post('http://127.0.0.1:3000/arraysum', json=data)
# Convert response data to json
returned_data = res.json()
print(returned_data)
result = returned_data['result']
print("Sum of Array from Node.js:", result)
通过以下命令运行此脚本。
python talk.py
输出:
{'result': 55}
Sum of Array from Node.js: 55
2. 使用后台进程:在下面的例子中,我们将通过从 Node.js 生成一个Python进程来进行通信,反之亦然,并监听stdout流。
Node.js to Python:从 node.js 调用Python进程。它包括以下步骤:
- 调用Python进程并将 JSON 数据作为命令行参数传递。
- 在Python读取该数据,对其进行处理,然后以 JSON 格式将其输出到stdout流。
- 再次从 node.js 读取输出流并处理 JSON 数据。
数组和.py
import sys, json
# Function to calculate the sum of array
def arraysum(arr):
return sum(arr)
# Get the command line arguments
# and parse it to json
data = json.loads(sys.argv[1])
# Get the required field from
# the data
array = data['array']
# Calculate the result
result = arraysum(array)
# Print the data in stringified
# json format so that we can
# easily parse it in Node.js
newdata = {'sum':result}
print(json.dumps(newdata))
现在Python将处理数组的总和并将其打印到标准输出,如下面的代码所示。
调用者.js
const spawn = require('child_process').spawn;
// Initialise the data
const data = {
array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
// We need to stringify the data as
// python cannot directly read JSON
// as command line argument.
let stringifiedData = JSON.stringify(data);
// Call the python process and pass the
// data as command line argument.
const py = spawn('python', ['arraysum.py', stringifiedData]);
resultString = '';
// As the stdout data stream is chunked,
// we need to concat all the chunks.
py.stdout.on('data', function (stdData) {
resultString += stdData.toString();
});
py.stdout.on('end', function () {
// Parse the string as JSON when stdout
// data stream ends
let resultData = JSON.parse(resultString);
let sum = resultData['sum'];
console.log('Sum of array from Python process =', sum);
});
通过以下命令运行此脚本:
node caller.js
输出:
Sum of array from Python process = 55
Python到 Node.js:从Python调用 node.js 进程。这些步骤基本上与上面提到的相同,但Python和 node.js 互换了它们的角色。
数组和.js
// Function to calculate sum of array
function arraysum(arr) {
let sum = 0;
for (var i = 0; i < arr.length; i++) {
if (isNaN(arr[i])) {
continue;
}
sum += arr[i];
}
return sum;
}
// Get the command line arguments and
// parse it to json
var data = JSON.parse(process.argv[2]);
// Get the required field form the data.
array = data['array'];
// Calculate the result.
var sum = arraysum(array);
// Print the data in stringified json
// format so that we can easily parse
// it in Python
const newData = { sum }
console.log(JSON.stringify(newData));
现在从Python运行这个 Node.js 进程。
文件名:caller.py
蟒蛇3
from subprocess import Popen, PIPE
import json
# Initialise the data
array = [1,2,3,4,5,6,7,8,9,10]
data = {'array':array}
# Stringify the data.
stingified_data = json.dumps(data)
# Call the node process and pass the
# data as command line argument
process = Popen(['node', 'arraysum.js',
stingified_data], stdout=PIPE)
# This line essentially waits for the
# node process to complete and then
# read stdout data
stdout = process.communicate()[0]
# The stdout is a bytes string, you can
# convert it to another encoding but
# json.loads() supports bytes string
# so we aren't converting
# Parse the data into json
result_data = json.loads(stdout)
array_sum = result_data['sum']
print('Sum of array from Node.js process =',array_sum)
通过以下命令运行此脚本。
python caller.py
输出:
Sum of array from Node.js process = 55