isbn-sort/app.py

99 lines
2.6 KiB
Python
Raw Normal View History

2024-04-03 18:30:04 +02:00
from flask import Flask, render_template, redirect, request, g, flash
import secrets
2024-04-03 16:54:54 +02:00
import json
from book import Book
import isbn_db
app = Flask(__name__)
app.config["DATABASE"] = "data/books.sqlite"
2024-04-03 18:30:04 +02:00
app.config["SECRET_KEY"] = secrets.token_hex()
2024-04-03 16:54:54 +02:00
@app.route("/submit-isbn")
def submit_isbn():
if "isbn" not in request.args:
return "/submit-isbn?isbn=xxxxxx"
2024-04-03 18:30:04 +02:00
if request.args["isbn"] == "":
return "Pas d'ISBN spécifié"
2024-04-03 16:54:54 +02:00
try:
book = Book(request.args["isbn"])
except ValueError:
return "Pas le bon format de QR code"
try:
book.load()
except KeyError:
isbn_db.add_book(book)
return "Pas trouvé, à rajouter manuellement"
print("Got ", book)
if isbn_db.add_book(book) == "duplicate":
return f"{book.title} ajouté (plusieurs occurrences)"
return f"{book.title} ajouté"
2024-04-03 18:30:04 +02:00
@app.route("/web-submit-isbn")
def web_submit_isbn():
flash(submit_isbn())
return redirect("/")
2024-04-03 17:54:20 +02:00
@app.route("/")
def index():
return render_template("index.html", books=isbn_db.get_all_books())
@app.route("/delete-book", methods=["POST"])
def delete_book():
if "isbn" not in request.form:
return "missing isbn"
isbn_db.delete_book(request.form["isbn"])
return redirect("/")
@app.route("/update-book", methods=["POST"])
def update_book():
attributes = ["isbn", "count", "title", "author", "publisher", "publish_date"]
if True in [i not in request.form for i in attributes]:
return "missing an attribute"
form_data = request.form.copy()
for attribute in attributes:
if form_data[attribute] == "None":
form_data[attribute] = None
book = Book(form_data["isbn"])
book._manual_load(
form_data["title"],
publisher=form_data["publisher"],
publish_date=form_data["publish_date"],
author=form_data["author"],
count=int(form_data["count"])
)
isbn_db.update_book(book)
return redirect("/")
2024-04-03 16:54:54 +02:00
2024-04-03 18:30:04 +02:00
@app.route("/export-csv")
def export_csv():
books = isbn_db.get_all_books()
csv = "ISBN;Titre;Auteur;Éditeur;Date;Nombre\n"
for book in books:
csv += f"{book.isbn};{book.title};{book.author};{book.publisher};{book.publish_date};{book.count}\n"
# return as file with a good filename
return app.response_class(
csv,
mimetype="text/csv",
headers={"Content-Disposition": "attachment;filename=books.csv"}
)
2024-04-03 16:54:54 +02:00
@app.after_request
def after_request(response):
"""Automatically close db after each request"""
if ('db' in g) and (g.db is not None):
g.db.close()
return response