简体   繁体   中英

Convert curl POST to urllib request python3

The following curl command works as intended. Uses POST to send a bit of information to a web site.

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

What should be the equivalent python3 code, gives an Error 500: Internal Server Error

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())

Already tried

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

Which gives "HTTP Error 422: Unprocessable Entity"

Any ideas on fixing it?

Thanks @cody

Lesson learned, PUT != POST

The following code works as expected:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM