将curl POST转换为urllib请求python3

时间:2019-01-16 22:06:28

标签: python-3.x curl post urllib

以下curl命令可按预期工作。使用POST将一些信息发送到网站。

    curl 'https://...' \
     -X PUT \
     -d "submission[posted_grade]=65" \
     -H "Authorization: Bearer 10~X" 

等效的python3代码应该是什么,给出错误500:内部服务器错误

url_string = 'https://...'
data = "submission[posted_grade]=40"
data = data.encode('utf-8')
req = urllib.request.Request(url_string, data)
req.add_header("Authorization", "Bearer 10~X")
req.add_header("Content-Type", "application/json")
response = urllib.request.urlopen(req)
print(response.read())

已经尝试

data = {'submission[posted_grade]': '40'}
data = json.dumps(data)
data = data.encode('utf-8')

给出“ HTTP错误422:无法处理的实体”

有任何修复建议吗?

1 个答案:

答案 0 :(得分:0)

感谢@cody

经验教训,PUT!= POST

以下代码按预期工作:

url_string = 'https://...'
data = "submission[posted_grade]=40"
data = data.encode('utf-8')
req = urllib.request.Request(url=url_string, data=data, method='PUT')
req.add_header("Authorization", "Bearer 10~X")
response = urllib.request.urlopen(req)