Setting a custom boundary for Python requests file uploads

714 Views Asked by At

Using the TinEye API requires setting a custom multipart boundary on requests. I can do that with urllib3, but I'd prefer doing that with Python requests. For urllib3, calling the TinEye API looks like that:

from hashlib import sha1
from PIL import Image
import hmac, json, mimetools, random, string, time, urllib, urllib3

def get_tineye_results(path):
    TINEYE_API_URL = 'http://api.tineye.com/rest/search/'
    TINEYE_PUBLIC_KEY = 'your-public-key'
    TINEYE_SECRET_KEY = 'your-secret-key'
    filename = path.replace('\\', '/').rsplit('/', 1)[1]
    t = int(time.time())
    nonce = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) # 8+ random characters
    boundary = mimetools.choose_boundary()
    to_sign = TINEYE_SECRET_KEY + 'POST' + 'multipart/form-data; boundary=' + boundary + urllib.quote_plus(filename) + str(t) + nonce + TINEYE_API_URL
    signature = hmac.new(TINEYE_SECRET_KEY, to_sign, sha1).hexdigest()
    data = { 'api_key': TINEYE_PUBLIC_KEY, 'date': t, 'nonce': nonce, 'api_sig': signature }
    r = urllib3.connection_from_url(TINEYE_API_URL).request_encode_body('POST', TINEYE_API_URL+'?'+ urllib.urlencode(data), fields={'image_upload': (filename, open(path, 'rb').read())}, multipart_boundary=boundary)
    return json.loads(r.data)

print get_tineye_results('/temp/my_image.jpg')

Problem is: I can't figure out a way to set the custom boundary in Python requests. There is an additional package for Python requests that supposedly allows this. But I prefer to do this only in Python requests, or with Python standard libs urllib + urllib2.

0

There are 0 best solutions below