响应'对象不可订阅 Python http post 请求
Response' object is not subscriptable Python http post request
我正在尝试 post HTTP
请求。我已经设法让代码工作,但我正在努力返回一些结果。
结果是这样的
{
"requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",
"numberOfRequests" : 1893
}
我正在尝试获取 requestId,但我一直收到错误 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"])
您应该将您的回复转换为字典:
requestpost = requests.post(url, json=data, auth=(username, password))
res = requestpost.json()
print(res["requestId"])
response
对象包含的信息远不止有效载荷。要获取 POST 请求返回的 JSON 数据,您必须按照 in the example:
所述访问 response.json()
requestpost = requests.post(url, json=data, auth=(username, password))
response_data = requestpost.json()
print(response_data["requestId"])
响应不可读,因此您需要将其转换为可读格式,
我正在使用 python http.client
conn = http.client.HTTPConnection('localhost', 5000)
payload = json.dumps({'username': "username", 'password': "password"})
headers = {'Content-Type': 'application/json'}
conn.request('POST', '/api/user/register', payload, headers)
response = conn.getresponse()
print("JSON - ", response.read())
如有要求,您可以查看上面的答案
有时您必须使用 json.loads()
函数来转换适当的格式。
我正在尝试 post HTTP
请求。我已经设法让代码工作,但我正在努力返回一些结果。
结果是这样的
{
"requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",
"numberOfRequests" : 1893
}
我正在尝试获取 requestId,但我一直收到错误 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"])
您应该将您的回复转换为字典:
requestpost = requests.post(url, json=data, auth=(username, password))
res = requestpost.json()
print(res["requestId"])
response
对象包含的信息远不止有效载荷。要获取 POST 请求返回的 JSON 数据,您必须按照 in the example:
response.json()
requestpost = requests.post(url, json=data, auth=(username, password))
response_data = requestpost.json()
print(response_data["requestId"])
响应不可读,因此您需要将其转换为可读格式, 我正在使用 python http.client
conn = http.client.HTTPConnection('localhost', 5000)
payload = json.dumps({'username': "username", 'password': "password"})
headers = {'Content-Type': 'application/json'}
conn.request('POST', '/api/user/register', payload, headers)
response = conn.getresponse()
print("JSON - ", response.read())
如有要求,您可以查看上面的答案
有时您必须使用 json.loads()
函数来转换适当的格式。