isbn-sort/isbn_sort/book.py

60 lines
1.9 KiB
Python
Raw Normal View History

2024-04-03 16:28:25 +02:00
import requests
import json
class Book:
def __init__(self, isbn):
if isbn is None:
return None
try:
2024-04-03 17:54:20 +02:00
isbn = str(isbn).replace("-", "")
2024-04-03 16:28:25 +02:00
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
2024-04-03 16:54:54 +02:00
self.count = -1
2024-04-03 16:28:25 +02:00
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]
2024-04-03 16:54:54 +02:00
2024-04-03 16:28:25 +02:00
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"]
2024-04-03 16:54:54 +02:00
def _manual_load(self, title, publisher=None, publish_date=None, author=None, count=-1):
2024-04-03 16:28:25 +02:00
self.title = title
self.publisher = publisher
self.publish_date = publish_date
self.author = author
2024-04-03 16:54:54 +02:00
self.count = count
2024-04-03 16:28:25 +02:00
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}>"