Python file upload - requests adds Content-* to files

Answered

5 Comments

  • Official comment
    Joey
    Comment actions Permalink

    One more thing, Scott-

    Using the following I received the appropriate JSON response, given me a token which could then be used to attach your upload to another object such as a ticket, etc.

    #!/usr/bin/python

    import sys
    import requests

    user = 'email@example.com/token'
    token = '{API_TOKEN}'
    url = 'https://{SUBDOMAIN}.zendesk.com/api/v2/uploads.json?filename={foo}'
    headers = {'Content-type': 'application/binary', 'Accept': 'text/plain'}

    uploaddata = '{foo}'

    s = requests.session()
    s.auth = (user, token)
    resp = s.post(url, headers = headers, data = uploaddata )

    print(resp.content)

    Certainly not production ready, but my test file was not overwritten as was in your case. Please give it a try!

  • Joey
    Comment actions Permalink

    Hi there Scott-

    Thanks for writing in. Given that this is not occurring with cURL, I would consider it unlikely Zendesk is writing this data to your file(s). I wanted to ask if you had seen the Zenpy Client Library. While not supported by us, the developer maintains it and is quite well-documented.

    Take care!

    0
  • Scott Laffer
    Comment actions Permalink

    Hi Joseph,

    Thanks for having a look. I 100% agree this is a Python problem, not a Zendesk one. :-)

    I had seen the Zenpy module, but honestly I wanted to try this myself and I don't believe it supported the OAuth2 authentication I've implemented in my app now.

    I see you're uploading the contents of the file using the data kwarg, not the files kwarg which I believe is normal to use with the Python requests module. Is there a particular reason for this?

    Scott

    0
  • Scott Laffer
    Comment actions Permalink

    Oh... For the record, the following code does work successfully.

    def upload_file(self, file_list):
    self.token = ""
    self.headers["Content-Type"] = "application/binary"
    for file in file_list:
    _filename = file.split("/")[-1]
    self.url = "https://{0}.zendesk.com/api/v2/uploads.json".format(self.baseurl)
    self.params = {"filename" : _filename, "token" : self.token}

    status = requests.post(self.url, headers=self.headers, data=open(file, 'rb').read(), params=self.params)
    self.logger.debug(pretty_print_POST(status.request))

    if status.status_code != 201:
    return False, status.text
    self.token = status.json()["upload"]["token"]
    return True, self.token
    0
  • Joe Gran
    Comment actions Permalink

    Scott - this saved me today. Thank you!!

    0

Please sign in to leave a comment.

Powered by Zendesk