isbn-sort/isbn_db.py
2024-04-03 17:54:20 +02:00

133 lines
3.0 KiB
Python

from flask import current_app
from flask import g
import sqlite3
from book import Book
def get_db():
"""Connect to the application's configured database. The connection
is unique for each request and will be reused if this is called
again.
"""
if "db" not in g:
g.db = sqlite3.connect(
current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def get_book(isbn):
db = get_db()
data = db.execute(
"""
SELECT * FROM book WHERE isbn=?
""",
(isbn,)
).fetchone()
if data is None:
raise IndexError("Book not in db")
book = Book(isbn)
book._manual_load(
data["title"],
publisher=data["publisher"],
publish_date=data["publish_date"],
author=data["author"],
count=data["count"]
)
return book
def delete_book(isbn):
db = get_db()
data = db.execute(
"""
DELETE FROM book WHERE isbn=?
""",
(isbn,)
)
db.commit()
def increment_count(book):
if book.count == -1:
book = get_book(book.isbn)
db = get_db()
db.execute(
"""
UPDATE book SET count=?
WHERE isbn=?
""",
(book.count+1, book.isbn)
)
db.commit()
def add_book(book):
try:
book = get_book(book.isbn)
increment_count(book)
return "duplicate"
except IndexError:
if book.count == -1:
book.count = 1
db = get_db()
db.execute(
"""
INSERT INTO book (isbn, count, title, author, publisher, publish_date)
VALUES (?, ?, ?, ?, ?, ?)
""",
(book.isbn, book.count, book.title, book.author, book.publisher, book.publish_date)
)
db.commit()
return "added"
def update_book(book):
db = get_db()
db.execute(
"""
UPDATE book SET count=?, title=?, author=?, publisher=?, publish_date=?
WHERE isbn=?
""",
(book.count, book.title, book.author, book.publisher, book.publish_date, book.isbn)
)
db.commit()
return "updated"
def get_all_books():
def count_none(book):
count = 0
if book.title is None:
count += 1
if book.author is None:
count += 1
if book.publish_date is None:
count += 1
if book.publisher is None:
count += 1
return -count
db = get_db()
data = db.execute(
"""
SELECT * FROM book
"""
).fetchall()
books = []
for data_row in data:
book = Book(data_row["isbn"])
book._manual_load(
data_row["title"],
publisher=data_row["publisher"],
publish_date=data_row["publish_date"],
author=data_row["author"],
count=data_row["count"]
)
books.append(book)
return sorted(books, key=count_none)