requests and EchoSign

I am trying to post a file into EchoSign APIs and it works everywhere for me except for python-requests.

I have here the CURL command that works perfectly

curl -H "Access-Token: API_KEY" 
 -F File=@/home/user/Desktop/test123.pdf 
 https://secure.echosign.com/api/rest/v2/transientDocuments

and this is my requests function. It will upload the PDF file but with garbage whereas CURL works perfectly.

api_url = 'https://secure.echosign.com/api/rest/v2'

def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

   :param access_token: EchoSign Access Token
   :param file_path: Absolute or relative path to File
   :return string: Document ID

   """
    headers = {'Access-Token': access_token}

    url = api_url + '/transientDocuments'

    with open(file_path, 'rb') as f:
        files = {
            'File': f,
        }
        return requests.post(url, headers=headers, files=files).json().get('transientDocumentId')

What am I doing wrong?? I have tried posting the file as data instead of files too and still no different result

Thanks

EDIT

It worked when I added

data = {
    'Mime-Type': 'application/pdf',
    'File-Name': 'abc.pdf'
}

So, my new function would be:

def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

    :param access_token: EchoSign Access Token
    :param file_path: Absolute or relative path to File
    :return string: Document ID

    """
    headers = {
        'Access-Token': access_token,
    }
    data = {
        'Mime-Type': 'application/pdf',
        'File-Name': 'abc.pdf'
    }
    url = api_url + '/transientDocuments'
    files = {'File': open(file_path, 'rb')}
    return requests.post(url, headers=headers, data=data,
                         files=files).json().get('transientDocumentId')

这是它的工作原理

def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

    :param access_token: EchoSign Access Token
    :param file_path: Absolute or relative path to File
    :return string: Document ID

    """
    headers = {
        'Access-Token': access_token,
    }
    data = {
        'Mime-Type': 'application/pdf',
        'File-Name': 'abc.pdf'
    }
    url = api_url + '/transientDocuments'
    files = {'File': open(file_path, 'rb')}
    return requests.post(url, headers=headers, data=data,
                         files=files).json().get('transientDocumentId')

Try passing in the filename and mime-type, like so:

files = {
    'File': (
        os.path.basename(file_path),
        f,
        'application/pdf',
    )
}

References:

  • http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
  • man curl , see the --trace-file FILE argumet
  • Proper MIME media type for PDF files
  • 链接地址: http://www.djcxy.com/p/8196.html

    上一篇: 处置:“内联”和“附件”之间有什么区别?

    下一篇: 请求和EchoSign