Amazon Product API ItemLookup example with python3

This function returns a request about products. load_aws_keys() is not written here.

def get_amazon_xml(*asins):
    access_key, secret_key = load_aws_keys()
    verb = 'GET'
    endpoint = 'http://webservices.amazon.co.jp/onca/xml' # .co.jp in Japan / .com in US
    if access_key is None or secret_key is None:
        print('No access key is available.')
        sys.exit()
    asin = ','.join([str(i) for i in asins])
    query_dict = {'AWSAccessKeyId':access_key,
                 'AssociateTag':'asterisk37n-22',
                 'IdType':'ASIN',
                 'ItemId':asin,
                 'Operation':'ItemLookup',
                 'ResponseGroup':'Images,ItemAttributes,Offers',
                 'Service':'AWSECommerceService',
                 'Timestamp':datetime.datetime.utcnow().isoformat(),
                 'Version':'2013-08-01'}
    sorted_query = sorted(query_dict.items()) # order matters
    query_url = urlencode(sorted_query)
#     calcurate signature
    msg_HMAC_SHA256 = verb + '\n' + 'webservices.amazon.co.jp' + '\n' + '/onca/xml' +'\n' + query_url
    dig = hmac.new(secret_key.encode('utf-8'), msg=msg_HMAC_SHA256.encode('utf-8'), digestmod=hashlib.sha256).digest()
    signature = base64.b64encode(dig).decode()      # py3k-mode
    request_url = endpoint + '?' + query_url+'&Signature='+quote(signature)
    print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
    print('Request URL = ' + request_url)
    r = requests.get(request_url)
    print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
    print('Response code: %d\n' % r.status_code)
    print(r.text)
    return r 

コメント