1

Using Python and Requests, I am trying to upload a file to an API using multipart/form-data POST requests with a custom authentication mechanism (Just adding an 'Authentication-Token' header).

Here is the code I use:

import requests
from requests.auth import AuthBase

class MyAuth(AuthBase):

    def __init__(self, token):
        self.token = token

    def __call__(self, r):
        r.headers['Authentication-Token'] = self.token
        return r

token = "175a5607d2e79109539b490f0f8ffe60"
url = "https://my-ap.com/files"

r = requests.post(url,
                  files={'file':  open('qsmflkj.jpg', 'rb')},
                  data={'id': 151},
                  auth=MyAuth(token)
)

Unfortunately, this request causes the following exception on the server (the backend is using the Spring framework) :

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

I have tried a lot of things, like adding the header myself, but this seems to be the "right" way to do it, and it fails. I know that the API is used from various mobile clients, and hence, that it is possible to upload picture there. What could I do differently to be able to use this API in Python?

madewulf
  • 1,870
  • 4
  • 26
  • 41

1 Answers1

0

In the end, I never managed to do this with Requests, but I succeeded with urllib2 and the poster library:

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

import urllib2

register_openers()
token = "175a5607d2e79109539b490f0f8ffe60"

with open('qsmflkj.jpg', 'rb') as f:
    datagen, headers = multipart_encode({"file": f})
    headers['Authentication-Token'] = token
    request = urllib2.Request("https://myserver.com/files", \
                              datagen, headers)
    response = urllib2.urlopen(request)
madewulf
  • 1,870
  • 4
  • 26
  • 41