使用TinEye API需要在请求上设置自定义多部分边界。我可以用urllib3做到这一点,但我更喜欢用Python请求做到这一点。对于urllib3,调用TinEye API看起来像这样:
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')
问题是:我无法找到在Python请求中设置自定义边界的方法。对于Python请求,还有一个额外的package可以允许这样做。
但我更喜欢在Python requests
中使用 ,或者使用Python标准库urllib + urllib2
。