Skip to content

Instantly share code, notes, and snippets.

@mebiusbox
Last active December 31, 2019 14:22
Show Gist options
  • Save mebiusbox/a24ad6b5a8c60c26e8e46a6651d20859 to your computer and use it in GitHub Desktop.
Save mebiusbox/a24ad6b5a8c60c26e8e46a6651d20859 to your computer and use it in GitHub Desktop.
Get book information by ISBN10 or ISBN13 with google books API
import sys
import urllib.request
import urllib.parse
import json
import objectpath
import pyperclip
import re
# API Endpoint
API_URL = "https://www.googleapis.com/books/v1/"
# API
def api(path, data=None):
if data is not None:
data = urllib.parse.urlencode(data)
data = data.encode('utf-8')
headers = {}
try:
# print(API_URL + path)
req = urllib.request.Request(API_URL + path, data, headers)
res = urllib.request.urlopen(req)
result = json.loads(res.read().decode('utf-8'))
info = dict(res.info())
return (result, info)
except urllib.error.HTTPError as e:
print(e)
print(e.code)
print(e.reason)
def check10(isbn10):
if not len(isbn10) == 10:
return False
sum = 0
for i in range(9):
try:
c = int(isbn10[i])
except ValueError:
return False
sum += (10-i)*c;
result = 11 - (sum % 11)
return u'X' if result == 10 else str(result)
def validate10(isbn10):
digit = check10(isbn10)
if digit is not False:
print("{} - {}", isbn10, digit)
return True if digit == isbn10[-1:].upper() else False
return False
def check13(isbn13):
if not len(isbn13) == 13:
return False
sum = 0
for i in range(12):
try:
c = int(isbn13[i])
except ValueError:
return False
weight = 3 if i % 2 else 1
sum += weight * c
result = 10 - (sum % 10)
return u'0' if result == 10 else str(result)
def validate13(isbn13):
digit = check13(isbn13)
if digit is not False:
print("{} - {}", isbn13, digit)
return True if digit == isbn13[-1:] else False
return False
def isbn10to13(isbn10):
isbn13 = "978" + isbn10
return isbn13[:-1] + check13(isbn13)
def query(isbn):
if len(isbn) == 10:
isbn = isbn10to13(isbn)
if len(isbn) != 13:
print("invalid isbn {}", isbn)
return None
result, info = api("volumes?q=isbn:" + isbn)
# print(result)
return result
if __name__ == '__main__':
args = sys.argv
if len(args) <= 1:
print("book <isbn>")
quit()
columns = [
{
"path": "$..industryIdentifiers[@.type is 'ISBN_13'].identifier"
},
{
"path": "$..title"
},
{
"path": "$..authors"
},
{
"path": "$..publisher"
},
{
"path": "$..publishedDate",
"pattern": "^(....).*$",
"replace": "\\1"
},
{
"path": "$..industryIdentifiers[@.type is 'ISBN_10'].identifier",
"pattern": "^(.+)",
"replace": "http://www.amazon.co.jp/dp/\\1"
# "path": "$..infoLink"
}
]
# sep = ','
sep = '\t'
data = query(args[1])
if data is not None:
tree = objectpath.Tree(data)
totalItems = tree.execute("$.totalItems")
if totalItems > 0:
output = ""
for c in columns:
# print(c)
items = tuple(tree.execute(c['path']))
if len(items)>0:
q = items[0]
if "pattern" in c.keys():
q = re.sub(c['pattern'], c['replace'], q)
output += q
output += sep
print(output)
pyperclip.copy(output)
else:
print("Not found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment