【问题标题】:Return two responses in Flask/JavaScript在 Flask/JavaScript 中返回两个响应
【发布时间】:2016-09-13 01:00:24
【问题描述】:

我有一个 Flask/JavaScript 应用程序,我在其中获取表单的输入并将它们传递给 Flask 应用程序,以从 GoogleMaps API 检索距离信息,然后将生成的 JSON 返回到 JavaScript。这适用于原点的单个实例/目的地。

我想接收两个起点/终点输入并将两者都返回到我的 JavaScript,但不知道该怎么做。我仍在学习,但我的印象是我不能简单地在一个函数中返回两个值,所以我希望有人可以看看我所拥有的并告诉我获取 JSON 的最佳方法是什么两者都返回 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)

【问题讨论】:

    标签: javascript python json


    【解决方案1】:

    您需要将两个值都包装在一个字典中,然后返回该字典。

    payload = {
        "current_response": current_response,
        "future_response": future_response
    }
    
    return jsonify(payload)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2016-03-04
      相关资源
      最近更新 更多