2 回答
TA贡献1836条经验 获得超3个赞
修复了这个问题。
问题在于我如何将数据发送到服务器。这就是我所拥有的:
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
有两个值被传递。网址和数据。
问题如下:
数据格式不正确。这应该是:
data = json.dumps({"title": eventTitle, "date": eventDate})
我需要添加标题:
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
我需要将一个
data
值传递给服务器,而不是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贡献1790条经验 获得超9个赞
您在字符串对象中有 JSON 数据。尝试通过字符串的键从字符串中提取值将产生您所描述的错误
>>> 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
您需要先将字符串转换为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'
添加回答
举报