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: # this can be ISBN-10 pass # raise ValueError("ISBN must be an int") self.isbn = isbn self.title = None self.publisher = None self.publish_date = None self.author = None self.category = 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 _google_books_load(self, config): if config["GOOGLE_BOOKS_KEY"] is None: key_param = "" else: key_param = f"&key={config['GOOGLE_BOOKS_KEY']}" r = requests.get(f"https://www.googleapis.com/books/v1/volumes?q=isbn:{self.isbn}{key_param}") 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 data["totalItems"] == 0: raise KeyError("Not found in Google Books") item = data["items"][0] self.title = item["volumeInfo"]["title"] if "publisher" in item["volumeInfo"]: self.publisher = item["volumeInfo"]["publisher"] if "publishedDate" in item["volumeInfo"]: self.publish_date = item["volumeInfo"]["publishedDate"] if "authors" in item["volumeInfo"]: self.author = item["volumeInfo"]["authors"][0] def _manual_load(self, title, publisher=None, publish_date=None, author=None, count=-1, category=None): self.title = title self.publisher = publisher self.publish_date = publish_date self.author = author self.count = count self.category = category def load(self, config, loader="openlibrary"): if loader == "openlibrary": return self._openlibrary_load(config) elif loader == "google_books": return self._google_books_load(config) else: raise ValueError("Invalid loader") def __repr__(self): if self.title is None: return f"" return f"" def to_json(self): return { "isbn": self.isbn, "title": self.title, "publisher": self.publisher, "publish_date": self.publish_date, "author": self.author, "category": self.category, "count": self.count, }