isbn-sort/isbn_db.py

77 lines
1.7 KiB
Python
Raw Normal View History

2024-04-03 16:54:54 +02:00
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 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"