0

So I am working on sending images to an url. And I planned to use Python to make the POST requests. My code looks like this:

import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'}

response = requests.request('POST', url, headers=headers, files={'file':open('1-watermarked-page.PNG', 'rb')})
print (response.status_code)

When I run this, I am getting a status code of 500. I tried to replace the "files" parameter by "data" and it gives me an error of 413: import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'}
response = requests.request('POST', url, headers=headers, data={'file':open('1-watermarked-page.PNG', 'rb')})
print (response.status_code)

Can anyone please tell me where am I making a mistake?

Thanks!

user5497505
  • 73
  • 1
  • 9
  • There's something wrong with the server try again later. And for 413, your file was larger then what the server expected – Taku Mar 17 '17 at 08:15
  • You should probably use [`requests.post()`](http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file). But yeah 413 means the file is too big – Markus Meskanen Mar 17 '17 at 08:19
  • @abccd, I mean when I change the "files" parameter with "data" parameter, keep everything the same, the status code changed from 500 to 413. – user5497505 Mar 17 '17 at 08:24
  • @MarkusMeskanen, I tried using requests.post(), it shows the same behaviour. – user5497505 Mar 17 '17 at 08:25
  • Status code 500 is server error, not yours. Are you sure the URL is POSTable? Did you try the same with the browser? Does server return any text with the 500 status code? – leovp Mar 17 '17 at 08:35
  • @leovp, my colleague used postman as chrome extension and it works. No, there is no text with the status code. – user5497505 Mar 17 '17 at 09:58

1 Answers1

1

The problem is that we have to send the data to a post request in the JSON format but we are sending it as a dictionary which makes the request a bad request. So the best approach known to me is to convert the data to JSON format (this might be because of the parsing that takes place at the server side)

import json
data = data={'file':open('1-watermarked-page.PNG', 'rb')}
response = request.post("url",json.dumps(data))
# json.dumps(data) converts data to json format

This worked for me, let me know if it worked for you