【问题标题】:Get Specific Data form request.post response in Python在 Python 中获取特定数据表单 request.post 响应
【发布时间】:2015-01-21 09:34:41
【问题描述】:

我正在使用 sendgrid api 向用户发送电子邮件,然后检查状态,

res = requests.post(url)
print type(res)

并将类型打印为<class 'requests.models.Response'>

在 Postman API 客户端我得到这个:

{
"message": "error",
"errors": [
"JSON in x-smtpapi could not be parsed"
]
}

我只想从响应中获取 message 值。我已经编写了以下代码但不起作用:

for keys in res.json():
    print str(res[keys]['message'])

【问题讨论】:

    标签: python api request sendgrid


    【解决方案1】:

    你不需要循环;只需访问由response.json() 方法返回的字典上的'message' 键:

    print res.json()['message']
    

    通过将response.json() 调用的结果存储在单独的变量中,可能更容易跟踪正在发生的事情:

    json_result = res.json()
    print json_result['message']
    

    Postman API 返回错误消息的原因是您的 POST 实际上没有包含任何数据;您可能想向 API 发送一些 JSON:

    data = some_python_structure
    res = requests.post(url, json=data)
    

    当您使用json 参数时,requests 库会为您将其编码为 JSON,并设置正确的内容类型标头。

    【讨论】:

      猜你喜欢
      • 2020-04-01
      • 2017-11-07
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2021-12-19
      • 2018-08-03
      • 2021-03-10
      • 2021-06-30
      相关资源
      最近更新 更多