Reputation: 57
I have a Flask/JavaScript application wherein I take a form's inputs and pass them to a Flask app to retrieve distance information from the GoogleMaps API and subsequently return the resulting JSON to JavaScript.This works fine for a single instance of an origin/destination.
I want to receive two origin/destination inputs and return both to my JavaScript but cannot figure out how to do that. I'm still learning, but am under the impression I can't simply return two values in a single function so I'm hoping someone can take a look at what I have and tell me what the best approach would be to get the JSON for both back to JavaScript.
@app.route("/", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
# form inputs
origin = request.form.get('origin')
destination = request.form.get('destination')
current_home = request.form.get('current_home')
future_home = request.form.get('future_home')
# current traffic conditions set to now
departure = int(time.time())
# params we pass to the url
current_params = {
'origins': origin,
'destinations': destination,
'mode':'driving',
'units':'imperial',
'departure_time' : departure,
'traffic_model':'best_guess',
'avoid':'tolls'
}
future_params = {
'origins': future_home,
'destinations': destination,
'mode':'driving',
'units':'imperial',
'departure_time' : departure,
'traffic_model':'best_guess',
'avoid':'tolls'
}
# api call
current_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'+ urllib.urlencode(current_params)
future_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'+ urllib.urlencode(future_params)
current_response = requests.get(current_url)
future_response = requests.get(future_url)
# return json
return jsonify(current_response.json())
return jsonify(future_response.json())
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Upvotes: 2
Views: 2734
Reputation: 136
You need to wrap both values in a dict and then return the dict.
payload = {
"current_response": current_response,
"future_response": future_response
}
return jsonify(payload)
Upvotes: 2