「10日で覚えるPython入門教室」に取り組む日曜日の午後。

第3日1時限目で停滞。
原因はAmazonAPIの仕様変更。
従来のアクセス方法では,APIを呼ぶことができず,従前のパラメータにSignatureとTimestampを付す必要がある。

ざっと検索してみたけれど,躓きの石状態で直接の解決策未発見。
仕方ないので,本に載っているコードを書き直し。

#! /usr/bin/env python
# coding:utf-8

import base64
import hashlib
import hmac
import urllib

from datetime import datetime
from xml.etree.ElementTree import ElementTree

# Amazon Product Advertising API Version.
# see http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=17
api_version = "2009-11-01"

def main(url):
    node_uri = "{http://webservices.amazon.com/AWSECommerceService/" + api_version + "}"

    xmlfile = urllib.urlopen(url)
    tree = ElementTree(file = xmlfile)
    root = tree.getroot()

    for node in root.getchildren():
        if node.tag == node_uri + "Items":
            for subnode in node.getchildren():
                if subnode.tag == node_uri +"TotalResults":
                    print subnode.text
                elif subnode.tag == node_uri +"Item":
                    for item in subnode:
                        if item.tag == node_uri +"ASIN":
                            print item.text

if __name__ == "__main__":
    amazon_api_url = "http://ecs.amazonaws.jp/onca/xml?"

    #Your Amazon API secret key.
    SecretKey = "★★★"

    # initialize Dictionary
    params = {}

    params["Service"] = "AWSECommerceService"
    params["Operation"] = "ItemSearch"
    params["Version"] = api_version
    params["AWSAccessKeyId"] = "★★★" #YOUR AWS Access Key Id
    params["SearchIndex"] = "Books"
    params["Keywords"] = "Python"

    #Amazon Product Advertising API requires a timestamp and a signature
    #see http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?rest-signature.html
    #see http://www.python.jp/doc/2.5/lib/module-datetime.html
    params["Timestamp"] = datetime.utcnow().isoformat()

    #creating the string to sign
    string = string_base = "GET\necs.amazonaws.jp\n/onca/xml\n"
    for k,v in sorted(params.items()):
        if string <> string_base:
            string = string + '&'
        string = string + k + '=' + urllib.quote(v)

    #calculate HMAC with the SHA256 hash with using Secret Key
    string = hmac.new(SecretKey, string, hashlib.sha256).digest()
    signature = base64.b64encode(string)

    url = amazon_api_url
    for k,v in sorted(params.items()):
        url = url + k + '=' + v + '&'
    url = url + 'Signature=' + urllib.quote(signature)

    main(url)

URLの作り方など,もっと簡単にできそうだけれども,Amazonの仕様説明に忠実な処理で作成してみました。

<同じ問題で困ったと思われる方々>
Amazon API仕様変更してて使えない(-_-)『10日でおぼえるPython入門教室』第3日 メモ
Python再び・・・・ハッシュを辞書と読んでるんですねぇー
TwitterAPI
Pythonのお勉強~三日目(Web API編①)
http://twitter.com/t2enonu/status/5621601942

翔泳社さん,ここだけでも早めに改定した方が良いですよ。
良い本なのですから。

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes