django - How can I translate a curl command to Python request?
Solution:
You need to pass an opened file object (likely in binary mode). Don't pass just the filename: passopen(request.FILES['filename'], 'rb')
as second argument touploadImage()
.
Although it's a bit surprising that requests doesn't raise an error when passed a string for thefiles
input. But I assume a string is just file contents for requests, albeit in non-binary mode, so requests doesn't notice the difference.
Answer
Solution:
Turns out the file has to be opened in binary mode. I didn't open the file
def uploadImage(stagedTarget, file):
# Get the permannent access_token
parameters = stagedTarget["parameters"]
url = stagedTarget["url"]
files = {
'Content-Type': parameters[0]['value'],
'success_action_status': parameters[1]['value'],
'acl': parameters[2]['value'],
'key': parameters[3]['value'],
'x-goog-date': parameters[4]['value'],
'x-goog-credential': parameters[5]['value'],
'x-goog-algorithm': parameters[6]['value'],
'x-goog-signature': parameters[7]['value'],
'policy': parameters[8]['value'],
'file': file.open(mode='rb'),
}
response = requests.post(url, files=files)
print(f"{response.status_code = }")
print(f"{response.text = }")
response = response.content
response = json.loads(response)
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.