我正在尝试修改 Postman 生成的这段代码,以用字符串变量替换硬编码字符串,但我不断收到KeyError: '\n\t"username"'这是代码username = "jose"email = "some_email"password = "1234"url = "some_url"payload = '{\n\t\"username\": {},\n\t\"email\": {},\n\t\"password\": {}\n}'.format(username, email, password)headers = { 'Content-Type': 'application/json'}response = requests.request("POST", url, headers=headers, data=payload)print(response.text.encode('utf8'))
2 回答
Helenr
TA贡献1780条经验 获得超4个赞
你可以这样正确地形成你的json:
import json
username = "jose"
email = "some_email"
password = "1234"
url = "some_url"
payload = json.dumps({"username": username, "email":email, "password":password}, indent=4)
headers = { 'Content-Type': 'application/json'}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text.encode('utf8'))
长风秋雁
TA贡献1757条经验 获得超7个赞
看看这里的例子:https ://requests.readthedocs.io/en/master/user/quickstart/
>>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})
您可以只使用字典来获取数据。
添加回答
举报
0/150
提交
取消