Created
March 1, 2011 19:46
-
-
Save seikichi/849744 to your computer and use it in GitHub Desktop.
ISBNをAmazon APIに投げて自炊した本のタイトル向けの文字列を出力
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/ | |
from sys import argv | |
from time import gmtime, strftime | |
from urllib import urlencode, urlopen | |
from xml.etree import ElementTree as ET | |
from base64 import b64encode | |
import hashlib, hmac | |
from StringIO import StringIO | |
API_HOST = 'webservices.amazon.co.jp' | |
API_PATH = '/onca/xml' | |
SERVICE = 'AWSECommerceService' | |
OPERATION = 'ItemLookup' | |
VERSION = '2010-11-01' | |
NAMESPACE = "{http://webservices.amazon.com/%s/%s}" % (SERVICE, VERSION) | |
if len(argv) != 4: | |
print("Usage: %s AccessKeyID SecretAccessKey ISBN" % argv[0]) | |
exit(-1) | |
ACCESS_KEY_ID = argv[1] | |
SECRET_ACCESS_KEY = argv[2] | |
ISBN = argv[3].replace('-', '') | |
query = sorted([ | |
('Service', SERVICE), | |
('Version', VERSION), | |
('Operation',OPERATION), | |
('Timestamp', strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())), | |
('AWSAccessKeyId', ACCESS_KEY_ID), | |
('IdType', "ISBN"), | |
('ItemId', ISBN), | |
('SearchIndex', "Books"), | |
]) | |
string_to_sign = '\n'.join(['GET', API_HOST, API_PATH, urlencode(query)]) | |
signature = b64encode(hmac.new(SECRET_ACCESS_KEY, string_to_sign, hashlib.sha256).digest()) | |
query.append(('Signature', signature)) | |
r = urlopen('http://'+API_HOST+API_PATH, urlencode(query)) | |
dom = ET.parse(StringIO(r.read())) | |
if dom.findall('//'+NAMESPACE+"Error"): | |
print("Error: ISBN=%s" % ISBN) | |
exit(-1) | |
manufacturer = dom.findtext('//'+NAMESPACE+"Manufacturer") | |
title = dom.findtext('//'+NAMESPACE+"Title") | |
author = [] | |
illustrator = [] | |
for creator in dom.findall('//'+NAMESPACE+"Creator"): | |
if creator.attrib['Role'] == u'著': | |
author.append(creator.text) | |
elif creator.attrib['Role'].find(u"イラスト") >= 0: | |
illustrator.append(creator.text) | |
else: | |
if not author: | |
author = [dom.findtext('//'+NAMESPACE+"Author")] | |
filename = ("[%s][%s][%s]%s.pdf" | |
% (manufacturer, ','.join(author), ','.join(illustrator), title)) | |
filename.replace(u'/', u'/') | |
# print(filename) | |
print(filename.encode('utf8')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment