-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookmanager.py
More file actions
85 lines (64 loc) · 2.09 KB
/
bookmanager.py
File metadata and controls
85 lines (64 loc) · 2.09 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from flask import Flask
from flask import render_template
from flask import request
import os
from flask_sqlalchemy import SQLAlchemy
from flask import redirect
# Database creation
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
db = SQLAlchemy(app)
# Define schema for our DB
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)
# api route --- api endpoint
# CREATE and READ
@app.route("/", methods = ['GET', 'POST'])
def home():
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()
print(books)
return render_template('home.html', books = books)
# UPDATE Endpoint
@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('Failed to update book')
print(e)
return redirect("/")
# DELETE Endpoint
@app.route("/delete", methods=["POST"])
def delete():
try:
title = request.form.get('title')
book = Book.query.filter_by(title=title).first()
db.session.delete(book)
db.session.commit()
except Exception as e:
print('Deletion failed')
print(e)
return redirect("/")
if __name__ == "__main__":
app.run(debug =True) # localhost
# To create the database, run the following commands in Python shell:
# >>> from bookmanager import db, app
# >>> with app.app_context():
# ... db.create_all() make sure to indent with 4 spaces, then press Enter twice
# >>> exit()