【问题标题】:FLASK - Show result from API call on same render page [duplicate]FLASK - 在同一渲染页面上显示 API 调用的结果 [重复]
【发布时间】:2021-07-05 19:25:34
【问题描述】:

我的 API 调用的响应文本显示在日志中,但我如何才能显示输出中的一个值。例如下面的返回结果。

{"uuid":"FqDSDSVJY+GYAHSTSGA=","id":6238236373}

我想在我的 index.html 页面上呈现“6238236373”。转换为有效的 json 对象然后将这些对象调用到我的页面上的最佳选择是什么?

app.py

@app.route('/alert', methods=['GET', 'POST'])
def alert():
    form = ReusableForm(request.form)
     
    if request.method == 'GET': 
    
        import requests

        url = "https://xxxxxxxxxxxxxxxxxxxxx.com/api/v1"

        payload="{}"
        headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json, application/xml',
        'Authorization': 'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        }

        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.text)
    
    return render_template('index.html', form=form,)

index.html

<html>
<body>

{ render id response }

</body>
</html>

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    鉴于您以 json 格式发送和接收数据,我认为您可以使用 jsonresult.text 转换为字典。

    import json
    #...
    data = json.loads(response.text)
    #...
    print(data['id']) # should output 6238236373
    

    关于jsonhere的更多信息。

    【讨论】:

      猜你喜欢
      • 2018-10-07
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多