-
Notifications
You must be signed in to change notification settings - Fork 10
/
bookmanager.py
66 lines (51 loc) · 1.71 KB
/
bookmanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "bookdatabase.db"))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
class Book(db.Model):
title = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
def __repr__(self):
return "<Title: {}>".format(self.title)
@app.route("/", methods=["GET", "POST"])
def home():
books = None
if request.form:
try:
book = Book(title=request.form.get("title"))
db.session.add(book)
db.session.commit()
except Exception as e:
print("Failed to add book")
print(e)
books = Book.query.all()
return render_template("home.html", books=books)
@app.route("/update", methods=["POST"])
def update():
try:
newtitle = request.form.get("newtitle")
oldtitle = request.form.get("oldtitle")
book = Book.query.filter_by(title=oldtitle).first()
book.title = newtitle
db.session.commit()
except Exception as e:
print("Couldn't update book title")
print(e)
return redirect("/")
@app.route("/delete", methods=["POST"])
def delete():
title = request.form.get("title")
book = Book.query.filter_by(title=title).first()
db.session.delete(book)
db.session.commit()
return redirect("/")
if __name__ == "__main__":
db.create_all()
app.run(host='0.0.0.0', port=8087, debug=True)