commit 77597d054f62a1d02d8fa7ab325735bf00e1ffb4 Author: augustin64 Date: Wed Apr 3 16:28:25 2024 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1023f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.venv +data +**/__pycache__ \ No newline at end of file diff --git a/book.py b/book.py new file mode 100644 index 0000000..085dec8 --- /dev/null +++ b/book.py @@ -0,0 +1,57 @@ +import requests +import json + +class Book: + def __init__(self, isbn): + if isbn is None: + return None + + try: + 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 + + 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): + self.title = title + self.publisher = publisher + self.publish_date = publish_date + self.author = author + + def load(self, loader="openlibrary"): + if loader == "openlibrary": + return self._openlibrary_load() + + def __repr__(self): + if self.title is None: + return f"" + return f"" \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c90b7f2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +flask +sqlite3 \ No newline at end of file