[英]Python Flask extracting results from endpoint
在下面的 Flask 腳本中,我想在我的端點“ /five
”中使用端點“ /three
”的結果。
' /three
' 的端點工作正常,但是當我嘗試端點 ' /five
' 時,我收到錯誤: TypeError: 'Response' object is not subscriptable
。
如何正確使用'/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)
如果您想通過 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.