In the Flask script below, I want to use the results of the endpoint '/three
' in my endpoint '/five
'.
The endpoint for '/three
' works fine, however when I try the endpoint '/five
', I get the error: TypeError: 'Response' object is not subscriptable
.
How do I correctly use the output of '/three' to compute '/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)
CodePudding user response:
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:
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)