我有这个代码用于向TinEye API发送查询:
from PIL import Image
from hashlib import sha1
import hmac, io, requests, string, urllib, urllib3
path = '/home/some/file.jpg'
limit = 10
TINEYE_API_URL = 'http://api.tineye.com/rest/search/'
TINEYE_PUBLIC_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
TINEYE_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
img = Image.open(path)
img.thumbnail((300, 300), Image.ANTIALIAS)
image_data = io.BytesIO()
img.save(image_data, img.format == 'PNG' and 'PNG' or 'JPEG', optimize=1, quality=88)
t = int(time.time())
nonce = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) # 8+ random characters
boundary = '--%s--' % nonce
to_sign = TINEYE_SECRET_KEY + 'POST' + 'multipart/form-data; boundary=' + boundary + 'image_data' + str(t) + nonce + TINEYE_API_URL + 'limit=%s' % limit
data = { 'api_key': TINEYE_PUBLIC_KEY, 'date': t, 'nonce': nonce, 'api_sig': hmac.new(TINEYE_SECRET_KEY, to_sign, sha1).hexdigest(), 'limit': limit }
r = urllib3.connection_from_url(TINEYE_API_URL).request_encode_body('POST', TINEYE_API_URL+'?'+ urllib.urlencode(data), fields={'image_upload': ('image_data', image_data.getvalue())}, multipart_boundary=boundary, timeout=5)
print r.data
我通常更喜欢Python请求库。但我不知道如何用请求lib编写urllib3.connection_from_url
部分。这可能吗?
这就是我所拥有的,但它不起作用:
headers = { 'Content-Type': 'multipart/form-data;boundary=' + boundary }
r = requests.post(TINEYE_API_URL, data=data, files={ 'image_data': image_data.getvalue() }, headers=headers, timeout=5)
print r.text