generated from Code-Institute-Org/gitpod-full-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
392 lines (315 loc) · 13.3 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
Diploma in Web Application Development: Backend (Data Centric) Development
Milestone Project 3 : CRUD app developed with the Flask mini-framework,
Materialize CSS and Mongo Atlas Database.
This MVP app allows registered users to store
information on plant seeds they wish to sow for the
coming year. A search facility enables them to see
which seeds should be sown in a particular month or
which plants are suitable as animal feed.
File name: app.py
Created: April, 2023
Author: Janet Dornan
Credit: Tim Nelson, Code Institite
Source: https://github.com/Code-Institute-Solutions/TaskManagerAuth
"""
import os
from functools import wraps
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
from decorators import login_required_admin, login_required_user
if os.path.exists("env.py"):
import env
app = Flask(__name__) # instance of Flask stored in variable 'app'
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
app.secret_key = os.environ.get("SECRET_KEY")
mongo = PyMongo(app)
@app.errorhandler(404)
def page_not_found(error_404):
'''
An error handler is registered with the errorhandler() decorator
for the status code 404 for page not found. Further info from:
https://flask.palletsprojects.com/en/2.2.x/errorhandling/
:param error_404: page not found error raised
:return: rendered template for the 404 page,
if an explicit error of 404 is raised
'''
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(error_500):
'''
An error handler is registered with the errorhandler() decorator
for the status code 500 internal server error. Further info from:
https://flask.palletsprojects.com/en/2.2.x/errorhandling/
:param error_500: Internal Server Error raised
:return: rendered template for the 500 page,
if an explicit error of 500 is raised
'''
return render_template('500.html'), 500
@app.route("/")
@app.route("/get_plants")
def get_plants():
'''
This function collects all the plant info from MongoDB.
This will be used for the home page
:return: Rendered home page, displaying all plants
'''
plants = list(mongo.db.plants.find().sort("plant_name", 1))
return render_template("plants.html", plants=plants)
@app.route("/about")
def about():
'''
This function displays the About and Instructions page
:return: Rendered about page
'''
return render_template("about.html")
@app.route("/search", methods=["GET", "POST"])
def search():
'''
This function enables the user to search through all plants
using key words in the fields plant name, description,
sow month and animal to feed.
:return: Rendered home page with the filtered plants
'''
query = request.form.get("query")
plants = list(mongo.db.plants.find({"$text": {"$search": query}}))
return render_template("plants.html", plants=plants)
@app.route("/search_profile", methods=["GET", "POST"])
def search_profile():
'''
This function enables the user to search through their own plants
using key words in the fields plant name, description,
sow month and animal to feed.
:return: Rendered profile page with the filtered plants
'''
query = request.form.get("query")
username = mongo.db.users.find_one(
{"username": session["user"]})["username"]
if session["user"]:
plants = list(mongo.db.plants.find({"$text": {"$search": query}}))
return render_template(
"profile.html", username=username, plants=plants)
plants = list(mongo.db.plants.find().sort("plant_name", 1))
return render_template("plants.html", plants=plants)
@app.route("/register", methods=["GET", "POST"])
def register():
'''
This function enables new users to register their name and password,
in order to create their own profile page.
Initially the function checks if the user exists,
if yes, they are told this and the register page reloads.
Otherwise the username and hashed password are added to the database.
New user's name is put into the session cookie and
they are sent to their profile page.
:return: register route, or
profile route for new user
'''
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"username": request.form.get("username").lower()})
if existing_user:
flash("Username already exists")
return redirect(url_for("register"))
register_user = {
"username": request.form.get("username").lower(),
"password": generate_password_hash(request.form.get("password"))
}
mongo.db.users.insert_one(register_user)
session["user"] = request.form.get("username").lower()
flash("Registration successful!")
return redirect(url_for("profile", username=session["user"]))
return render_template("register.html")
@app.route("/login", methods=["GET", "POST"])
def login():
'''
This function initially checks the db if the user is already registered;
if yes, the password is verified and they are greeted
with a welcome message on their profile page.
Otherwise they are directed to the register page if user does not exist
or the login page if the password is incorrect
:return: profile route if login successful, or
login route if password incorrect, or
register route if user does not exist
'''
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"username": request.form.get("username").lower()})
if existing_user:
if check_password_hash(
existing_user["password"], request.form.get("password")):
session["user"] = request.form.get("username").lower()
welcome = request.form.get("username").capitalize()
flash(f"Welcome, {welcome}")
session['logged_in'] = True
return redirect(url_for("profile", username=session["user"]))
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
return render_template("login.html")
@app.route("/profile/<username>", methods=["GET", "POST"])
@login_required_user
def profile(username):
'''
This function is wrapped with decorator which enforces user security
for protecting post owners.
Plant info is fetched from the db for the current logged in user.
:param username: session user's username retrieved from db
:return: rendered profile page for current user, or
login route if not
'''
username = mongo.db.users.find_one(
{"username": session["user"]})["username"]
if session["user"]:
plants = list(mongo.db.plants.find().sort("plant_name", 1))
return render_template(
"profile.html", username=username, plants=plants)
return render_template("404.html")
@app.route("/logout")
@login_required_user
def logout():
'''
This function is wrapped with decorator which enforces user security
- a user who is not logged in, should not be able to log out.
The current user will be removed from the session on logout and
redirected to the login page.
:return: login route
'''
flash("You have been logged out")
session.pop("user")
return redirect(url_for("login"))
@app.route("/add_plant", methods=["GET", "POST"])
@login_required_user
def add_plant():
'''
This function is wrapped with decorator which enforces user security
for protecting post owners.
This functionality enables the user to add plants to their profile page,
via the Add Plant form. If the form is submitted, then the plant dictionary
is written to the database.
:return: home page route
'''
if request.method == "POST":
is_edible = "on" if request.form.get("is_edible") else "off"
is_done = "on" if request.form.get("is_done") else "off"
plant = {
"category_name": request.form.get("category_name"),
"plant_name": request.form.get("plant_name").lower(),
"plant_description": request.form.get("plant_description"),
"sow": request.form.get("sow"),
"is_done": is_done,
"is_edible": is_edible,
"animal_name": request.form.get("animal_name"),
"link": request.form.get("link"),
"seed_link": request.form.get("seed_link"),
"created_by": session["user"]
}
mongo.db.plants.insert_one(plant)
flash("Plant Successively Added")
return redirect(url_for("get_plants"))
categories = mongo.db.categories.find().sort("category_name", 1)
months = mongo.db.months.find()
animals = mongo.db.animals.find().sort("animal_name", 1)
return render_template(
"add_plant.html",
categories=categories,
months=months,
animals=animals)
@app.route("/edit_plant/<plant_id>", methods=["GET", "POST"])
def edit_plant(plant_id):
'''
This function enables the user to edit their own plants,
via the Edit Plant form. If the form is submitted, then the plant
dictionary is written to the database.
:return: home page route
'''
plant = mongo.db.plants.find_one({"_id": ObjectId(plant_id)})
# Code from CI video DBMS Masterclass 2
if "user" not in session or session["user"] != plant["created_by"]:
return render_template('404.html')
if request.method == "POST":
is_edible = "on" if request.form.get("is_edible") else "off"
is_done = "on" if request.form.get("is_done") else "off"
submit = {
"category_name": request.form.get("category_name"),
"plant_name": request.form.get("plant_name").lower(),
"plant_description": request.form.get("plant_description"),
"sow": request.form.get("sow"),
"is_edible": is_edible,
"is_done": is_done,
"animal_name": request.form.get("animal_name"),
"link": request.form.get("link"),
"seed_link": request.form.get("seed_link"),
"created_by": session["user"]
}
mongo.db.plants.replace_one({"_id": ObjectId(plant_id)}, submit)
flash("Plant Successively Updated")
return redirect(url_for("get_plants"))
categories = mongo.db.categories.find().sort("category_name")
months = mongo.db.months.find()
animals = mongo.db.animals.find().sort("animal_name", 1)
return render_template(
"edit_plant.html",
plant=plant,
categories=categories,
months=months,
animals=animals)
@app.route("/delete_plant/<plant_id>", methods=["GET", "POST"])
def delete_plant(plant_id):
'''
This function enables the user to delete their own plants,
via the Delete button on their plant card.
:return: home page route
'''
plant = mongo.db.plants.find_one({"_id": ObjectId(plant_id)})
# Code from CI video DBMS Masterclass 2
if "user" not in session or session["user"] != plant["created_by"]:
return render_template('404.html')
if request.method == "POST":
mongo.db.plants.delete_one({"_id": ObjectId(plant_id)})
flash("Plant Successively Deleted")
return redirect(url_for("get_plants"))
return render_template("delete_plant.html", plant=plant)
@app.route("/get_categories")
@login_required_admin
def get_categories():
'''
This function is wrapped with decorator which enforces admin security
for protecting the administrator tasks.
Only the admin can view the categories page.
:return: rendered categories page for admin user only
'''
categories = list(mongo.db.categories.find().sort("category_name", 1))
return render_template("categories.html", categories=categories)
@app.route("/add_category", methods=["GET", "POST"])
@login_required_admin
def add_category():
'''
This function is wrapped with decorator which enforces admin security
for protecting the administrator tasks.
Only the admin can view and add a category.
:return: rendered categories page for admin user only
'''
if request.method == "POST":
existing_category = mongo.db.categories.find_one(
{"category_name": request.form.get("category_name").lower()})
if existing_category:
flash("Category Already Exists")
return redirect(url_for("get_categories"))
category = {
"category_name": request.form.get("category_name").lower()
}
mongo.db.categories.insert_one(category)
flash("New Category Added")
return redirect(url_for("get_categories"))
return render_template("add_category.html")
if __name__ == "__main__":
app.run(
host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug=os.environ.get("DEBUG"))