响应'对象不可下标Python http post请求 [英] Response' object is not subscriptable Python http post request

查看:32
本文介绍了响应'对象不可下标Python http post请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发布一个 HTTP 请求.我已经设法让代码工作,但我正在努力返回一些结果.

I am trying to post a HTTP request. I have managed to get the code to work but I am struggling returning some of the result.

结果是这样的

{
  "requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",
  "numberOfRequests" : 1893
}

我正在尝试获取 requestId,但我不断收到错误 Response' object is not subscriptable

I am trying to get the requestId but I keep getting the error Response' object is not subscriptable

import json
import requests

workingFile = 'D:\test.json'

with open(workingFile, 'r') as fh:
    data = json.load(fh)

url = 'http://jsontest'
username = 'user'
password = 'password123'

requestpost = requests.post(url, json=data, auth=(username, password))

print(requestpost["requestId"])

推荐答案

response 对象包含的信息远不止有效负载.要获取 POST 请求返回的 JSON 数据,您必须按照 在示例中:

The response object contains much more information than just the payload. To get the JSON data returned by the POST request, you'll have to access response.json() as described in the example:

requestpost = requests.post(url, json=data, auth=(username, password))
response_data = requestpost.json()
print(response_data["requestId"])

这篇关于响应'对象不可下标Python http post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆