2 回答

TA貢獻(xiàn)1836條經(jīng)驗 獲得超3個贊
修復(fù)了這個問題。
問題在于我如何將數(shù)據(jù)發(fā)送到服務(wù)器。這就是我所擁有的:
targetWikiPage = input("Target Wiki Page: ")
eventTitle = input("Event Title: ")
eventDate = input("Event Date: ")
#POST AN EVENT
data = '{"title": "'+eventTitle+'","date":"'+eventDate+'"}'
print("SENDING EVENT DATA:")
print(requests.body)
print(requests.headers)
response = requests.post("http://localhost:5002/events", json=data)
請注意,我的requests.post
有兩個值被傳遞。網(wǎng)址和數(shù)據(jù)。
問題如下:
數(shù)據(jù)格式不正確。這應(yīng)該是:
data = json.dumps({"title": eventTitle, "date": eventDate})
我需要添加標(biāo)題:
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
我需要將一個
data
值傳遞給服務(wù)器,而不是json
requests.post("http://localhost:5002/events", headers=headers, data=data)
這將我的文件更改為:
targetWikiPage = input("Target Wiki Page: ")
eventTitle = input("Event Title: ")
eventDate = input("Event Date: ")
#POST AN EVENT
data = json.dumps({"title": eventTitle, "date": eventDate})
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
print(data)
print(headers)
print("SENDING EVENT DATA:")
response = requests.post("http://localhost:5002/events", headers=headers, data=data)
json=json.loads(response.content)

TA貢獻(xiàn)1790條經(jīng)驗 獲得超9個贊
您在字符串對象中有 JSON 數(shù)據(jù)。嘗試通過字符串的鍵從字符串中提取值將產(chǎn)生您所描述的錯誤
>>> response = '{"date":"Sun, 23 Feb 2020 00:00:00 GMT","title":"TEst Event 3"}'
>>> response_date = response["date"]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
response_date = response["date"]
TypeError: string indices must be integers
您需要先將字符串轉(zhuǎn)換為a dict,然后提取值
>>> import json
>>> response_as_json = json.loads(response)
>>> response_date = response_as_json["date"]
>>> response_date
'Sun, 23 Feb 2020 00:00:00 GMT'
添加回答
舉報