将 curl PUT 转换为 Python 请求的问题:"Problems parsing JSON"

Issue translating curl PUT to Python requests: "Problems parsing JSON"

我想使用 Python requests library to create a new file in a GitHub 存储库。在命令行中输入以下内容对我有用(根据需要替换 LOGINTOKEN):

curl -X PUT -d '{"path": "testfile.txt", "message": "test", "content": "aGVsbG8y"}' https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt\?access_token\=TOKEN

但是当尝试对请求进行相同操作时,我一直 运行 进入 "Problems parsing JSON" 错误(状态代码 400):

data = {
    "message": "test",
    "content": "aGVsbG8y",
    "path": "testfile.txt"
}
url = "https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt?access_token={}".format(TOKEN)
response = requests.put(url, data=data)

关于我的不同之处的任何提示?我检查了类似的问题,但没有找到正确的调整。谢谢!

因为只要传递一个 data 参数就会自动将您的字典作为表单编码参数发送。而是将其作为 JSON

传递
import json
data = {
    "message": "test",
    "content": "aGVsbG8y",
    "path": "testfile.txt"
}
url = "https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt?access_token={}".format(TOKEN)
response = requests.put(url, data=json.dumps(data))

或者,如果您至少使用 2.4.2 版,您可以这样做:

response = requests.put(url, json=data)