“Bad Gateway” error using Python requests module with multipart encoded file POST


“Bad Gateway” error using Python requests module with multipart encoded file POST



I am getting the error message "Bad Gateway



The proxy server received an invalid
response from an upstream server" with the following code:


import requests

url = "https://apis.company.com/v3/media"
attachments = 'media': ('x.mp3', open('x.mp3', 'r'))}
headers = {'content-type': "multipart/form-data",'cache-control': "no-cache"
'Authorization':"Bearer zzz" }
response = requests.post(url, files=attachments, headers = headers)
print response.text



I'm following the example in the requests Quickstart documentation, where it says "You can also pass a list of tuples to the data argument": http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file



What is causing this error and how can I fix it?





@Goyo if I change "files" to "data", as in data = attachments, it doesn't change the error message. The client I'm using stipulates this: response = requests.post( self.client.url + '/media', headers = headers, files = attachments)
– topplethepat
Feb 5 at 21:14





Do you want to pass a data argument, a files argument or are you just throwing arguments at random?
– Goyo
Feb 5 at 21:17


data


files




1 Answer
1



The main problem was that I set the content-type in the header. This code works:


import requests

url = 'https://apis.company.com/v3/media'
token = 'token-goes-here'

headers = { 'Authorization' : 'Bearer ' + token }

filename = 'x.mp3'

with open(filename, 'rb') as media_file:

attachments = {
'media': (filename, media_file, 'application/octet-stream')
}

response = requests.post(url, files = attachments, headers = headers)

print response.text






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API