forked from mjhea0/flaskr-tdd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
121 lines (97 loc) · 3.08 KB
/
app.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# imports
import os
from functools import wraps
from flask import (
Flask,
request,
session,
redirect,
url_for,
abort,
render_template,
flash,
jsonify,
)
from flask_sqlalchemy import SQLAlchemy
# get the folder where this file runs
basedir = os.path.abspath(os.path.dirname(__file__))
# configuration
SECRET_KEY = "my_precious"
USERNAME = "admin"
PASSWORD = "admin"
# database config
SQLALCHEMY_DATABASE_URI = os.getenv(
"DATABASE_URL", f'sqlite:///{os.path.join(basedir, "flaskr.db")}'
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
# create app
app = Flask(__name__)
app.config.from_object(__name__)
db = SQLAlchemy(app)
import models
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in"):
flash("Please log in.")
return jsonify({"status": 0, "message": "Please log in."}), 401
return f(*args, **kwargs)
return decorated_function
@app.route("/")
def index():
"""Searches the database for entries, then displays them."""
entries = db.session.query(models.Flaskr)
return render_template("index.html", entries=entries)
@app.route("/add", methods=["POST"])
def add_entry():
"""Adds new post to the database."""
if not session.get("logged_in"):
abort(401)
new_entry = models.Flaskr(request.form["title"], request.form["text"])
db.session.add(new_entry)
db.session.commit()
flash("New entry was successfully posted")
return redirect(url_for("index"))
@app.route("/login", methods=["GET", "POST"])
def login():
"""User login/authentication/session management."""
error = None
if request.method == "POST":
if request.form["username"] != app.config["USERNAME"]:
error = "Invalid username"
elif request.form["password"] != app.config["PASSWORD"]:
error = "Invalid password"
else:
session["logged_in"] = True
flash("You were logged in")
return redirect(url_for("index"))
return render_template("login.html", error=error)
@app.route("/logout")
def logout():
"""User logout/authentication/session management."""
session.pop("logged_in", None)
flash("You were logged out")
return redirect(url_for("index"))
@app.route("/delete/<int:post_id>", methods=["GET"])
@login_required
def delete_entry(post_id):
"""Deletes post from database."""
result = {"status": 0, "message": "Error"}
try:
new_id = post_id
db.session.query(models.Flaskr).filter_by(post_id=new_id).delete()
db.session.commit()
result = {"status": 1, "message": "Post Deleted"}
flash("The entry was deleted.")
except Exception as e:
result = {"status": 0, "message": repr(e)}
return jsonify(result)
@app.route("/search/", methods=["GET"])
def search():
query = request.args.get("query")
entries = db.session.query(models.Flaskr)
if query:
return render_template("search.html", entries=entries, query=query)
return render_template("search.html")
if __name__ == "__main__":
app.run()