Python Flask extracting results from endpoint

Issue

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)

Solution

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)

Answered By – ilias-sp

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published