python - 如何将我的变量分配给我的 API 的字符串响应?
问题描述
我正在向 Python 烧瓶 api 发送一个发布请求。我正在返回 200 并且响应的正文正确记录在控制台中。但是,当我尝试将它传递给“响应”变量以存储它未分配的变量时。
我试图记录响应变量并查看实际传递给它的内容。如果我尝试在请求调用中将它记录到控制台,它会显示它成功地有一个字符串。但是当我将它记录到请求之外的控制台时,它显示为未定义?
这是我的 Node.js 正在调用
function handleMessage(sender_psid, received_message) {
let response;
request({
"uri": "http://localhost:8090/givenMessage",
"method": "POST",
"json": received_message
}, (err, res, body) => {
if (!err) {
console.log('message sent to python!')
console.log(typeof body)
var string = JSON.stringify(body);
var objectValue = JSON.parse(string);
response = body; //parse the json body to string keep body in
} else {
console.error("Unable to send message to python:" + err);
}
});
// Check if the message contains text
/*if (received_message.text) {
// Create the payload for a basic text message
response = {
"text": `You sent the message: "${received_message.text}".`
}
} */
// Sends the response message
callSendAPI(sender_psid, response);
}
这是我的 python 后处理程序
from flask import Flask
from flask import request
app = Flask(__name__) #create the app server to recieve post
@app.route('/givenMessage', methods = ['POST'])
def postJsonHandler():
print (request.is_json)
content = request.get_json()
print (content)
return 'JSON posted'
app.run(host = '0.0.0.0', port = 8090)
现在,当我将响应变量传递给 callSendAPI 方法时,它只是未定义。我希望它从我的 python post 调用中输出字符串 'JSON posted'
解决方案
对不起,我回答了。发布请求很慢,因此响应变量没有时间分配。它是异步调用的。我只是将我的方法放在 if 语句中以等待发布响应
推荐阅读
- node.js - Node-oracledb TypeError:oracledb.getConnection 不是函数
- sed - 使用 sed 替换为带有特殊字符的 var
- python-3.x - 超像素opencv2中的阈值
- reactjs - react - useState 从不更新值
- basic-authentication - Pushgateway 抛出 401 - 未经授权
- ios - 只要我没有删除派生数据,就找不到此可执行文件的有效配置文件
- angular - 在 Angular 函数中等待 Observable
- c# - 如何将c#中的列表转换为javascript .net核心中的数组
- python - 在 xlsxwriter python 中使用输入函数创建多张工作表
- arrays - 在 postgres 表中使用字符串数组转换列以在 row.in_ 过滤器中使用它