Initial commit
This commit is contained in:
commit
77597d054f
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
.venv
|
||||
data
|
||||
**/__pycache__
|
57
book.py
Normal file
57
book.py
Normal file
@ -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"<Book: ISBN:{self.isbn}>"
|
||||
return f"<Book: {self.title}>"
|
2
requirements.txt
Normal file
2
requirements.txt
Normal file
@ -0,0 +1,2 @@
|
||||
flask
|
||||
sqlite3
|
Loading…
Reference in New Issue
Block a user