[英]Python Flask extracting results from endpoint
In the Flask script below, I want to use the results of the endpoint ' /three
' in my endpoint ' /five
'.在下面的 Flask 脚本中,我想在我的端点“
/five
”中使用端点“ /three
”的结果。
The endpoint for ' /three
' works fine, however when I try the endpoint ' /five
', I get the error: TypeError: 'Response' object is not subscriptable
. '
/three
' 的端点工作正常,但是当我尝试端点 ' /five
' 时,我收到错误: TypeError: 'Response' object is not subscriptable
。
How do I correctly use the output of '/three' to compute '/five'?如何正确使用'/three'的output来计算'/five'?
from flask import Flask, url_for, redirect
app = Flask(__name__)
@app.route('/three')
def three():
return {'message':3}
@app.route('/five')
def five():
old_message = redirect(url_for('three'))['message'] # expect to return 3
new_message = {'message':old_message + 2 } # 3+2 = 5
return new_message # expecting {'message':5}
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
if you want to trigger the three
method via http request, you could use requests
package, then JSON-parse it, manipulate and return to the client:如果您想通过 http 请求触发这
three
方法,您可以使用requests
package,然后对其进行 JSON 解析,操作并返回给客户端:
from flask import jsonify
import requests
import json
...
...
...
@app.route('/three')
def three():
return {'message':3}
@app.route('/five')
def five():
http_req = requests.get('http://localhost:8000/three')
my_three_json = json.loads(http_req.text)
my_three_json["message"] += 2
return jsonify(my_three_json)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.