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.owner = None self.status = 0 self.author = None self.category = None @property def status_text(self) -> str: return [ "À lire", "En cours", "Lu" ][self.status] 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 "authors" in isbn_data["details"] and len(isbn_data["details"]["authors"]) > 0: self.author = isbn_data["details"]["authors"][0]["name"] 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 "authors" in item["volumeInfo"]: self.author = item["volumeInfo"]["authors"][0] def _manual_load(self, title, author=None, category=None, status=0, owner=None): self.title = title self.author = author self.category = category self.status = status self.owner = owner 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, "owner": self.owner, "status": self.status, "status_text": self.status_text, "author": self.author, "category": self.category } def replace(self, pattern, replacement): """Replace element in all fields""" def rep(el): if isinstance(el, str): return el.replace(pattern, replacement) return el self.isbn = rep(self.isbn) self.title = rep(self.title) self.owner = rep(self.owner) self.status = rep(self.status) self.author = rep(self.author) self.category = rep(self.category)