70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
import requests
|
|
import json
|
|
|
|
class Book:
|
|
def __init__(self, isbn):
|
|
if isbn is None:
|
|
return None
|
|
|
|
try:
|
|
isbn = str(isbn).replace("-", "")
|
|
int(isbn)
|
|
except ValueError:
|
|
raise ValueError("ISBN must be an int")
|
|
|
|
self.isbn = isbn
|
|
self.title = None
|
|
self.publisher = None
|
|
self.publish_date = None
|
|
self.author = None
|
|
self.count = -1
|
|
|
|
def _openlibrary_load(self):
|
|
r = requests.get(f"https://openlibrary.org/api/books?bibkeys=ISBN:{self.isbn}&jscmd=details&format=json")
|
|
|
|
if r.status_code != 200:
|
|
raise requests.RequestException(f"Got an error on the request. Status code: {r.status_code}")
|
|
|
|
data = json.loads(r.content)
|
|
|
|
if f"ISBN:{self.isbn}" not in data:
|
|
raise KeyError("Not found in OpenLibrary")
|
|
|
|
isbn_data = data[f"ISBN:{self.isbn}"]
|
|
|
|
self.title = isbn_data["details"]["title"]
|
|
if "publishers" in isbn_data["details"] and len(isbn_data["details"]["publishers"]) > 0:
|
|
self.publisher = isbn_data["details"]["publishers"][0]
|
|
|
|
if "authors" in isbn_data["details"] and len(isbn_data["details"]["authors"]) > 0:
|
|
self.author = isbn_data["details"]["authors"][0]["name"]
|
|
|
|
if "publish_date" in isbn_data["details"]:
|
|
self.publish_date = isbn_data["details"]["publish_date"]
|
|
|
|
|
|
def _manual_load(self, title, publisher=None, publish_date=None, author=None, count=-1):
|
|
self.title = title
|
|
self.publisher = publisher
|
|
self.publish_date = publish_date
|
|
self.author = author
|
|
self.count = count
|
|
|
|
def load(self, loader="openlibrary"):
|
|
if loader == "openlibrary":
|
|
return self._openlibrary_load()
|
|
|
|
def __repr__(self):
|
|
if self.title is None:
|
|
return f"<Book: ISBN:{self.isbn}>"
|
|
return f"<Book: {self.title}>"
|
|
|
|
def to_json(self):
|
|
return {
|
|
"isbn": self.isbn,
|
|
"title": self.title,
|
|
"publisher": self.publisher,
|
|
"publish_date": self.publish_date,
|
|
"author": self.author,
|
|
"count": self.count
|
|
} |