-
Notifications
You must be signed in to change notification settings - Fork 3
/
recipe.py
448 lines (388 loc) · 18.7 KB
/
recipe.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import os
import math
from flask_pymongo import PyMongo, pymongo # Flask connect to MongoDB Atlas
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
from flask import (Flask, render_template, redirect, request, url_for, flash,
session)
from forms import LoginForm, RegistrationForm, RecipeForm
"""
MongoDB represents JSON documents in binary-encoded format called
BSON behind the scenes. BSON extends the JSON model to provide
additional data types, ordered fields, and to be efficient
for encoding and decoding within different languages.
"""
if os.path.exists("env.py"):
import env
app = Flask(__name__)
"""
Environment variables SECRET and MONGO_URI set in Heroku
dashboard in production.
"""
app.config['SECRET_KEY'] = os.getenv("SECRET")
app.config["MONGO_URI"] = os.getenv("MONGO_URI")
app.config["MONGO_DBNAME"] = "virtual_cookbook"
mongo = PyMongo(app)
@app.route('/')
def index():
count_tasks = mongo.db.tasks.find().count()
favourite_count = mongo.db.tasks.find({'favourite': True}).count()
"""
Route allows users to view all the recipes within the database
collection. Logged in users can view own profile, create, edit
& delete recipes.
"""
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('index.html', count_tasks=count_tasks,
favourite_count=favourite_count, tasks=task,
title='Home', current_user=current_user)
else:
return render_template('index.html', count_tasks=count_tasks,
favourite_count=favourite_count, tasks=task,
title='Home')
@app.route('/meat', methods=['GET'])
def meat():
count_meat_tasks = mongo.db.tasks.find({"category_name": "Meat"}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('meat.html', count_meat_tasks=count_meat_tasks,
page_title='Meat Recipes',
current_user=current_user,
tasks=mongo.db.tasks.find
({"category_name": "Meat"}))
else:
return render_template('meat.html', count_meat_tasks=count_meat_tasks,
page_title="Meat Recipes",
tasks=mongo.db.tasks.find
({"category_name": "Meat"}))
@app.route('/poultry', methods=['GET'])
def poultry():
count_poultry_tasks = mongo.db.tasks.find({"category_name": "Poultry"}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('poultry.html',
count_poultry_tasks=count_poultry_tasks,
page_title='Poultry Recipes',
current_user=current_user,
tasks=mongo.db.tasks.find
({"category_name": "Poultry"}))
else:
return render_template("poultry.html",
count_poultry_tasks=count_poultry_tasks,
page_title="Poultry Recipes",
tasks=mongo.db.tasks.find
({"category_name": "Poultry"}))
@app.route('/fish', methods=['GET'])
def fish():
count_fish_tasks = mongo.db.tasks.find({"category_name": "Fish"}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('fish.html', count_fish_tasks=count_fish_tasks,
page_title='Fish Recipes',
current_user=current_user,
tasks=mongo.db.tasks.find
({"category_name": "Fish"}))
else:
return render_template("fish.html", count_fish_tasks=count_fish_tasks,
page_title="Fish Recipes",
tasks=mongo.db.tasks.find
({"category_name": "Fish"}))
@app.route('/veg', methods=['GET'])
def veg():
count_veg_tasks = mongo.db.tasks.find({"category_name": "Vegetables"}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('veg.html', count_veg_tasks=count_veg_tasks,
page_title='Vegetable Recipes',
current_user=current_user,
tasks=mongo.db.tasks.find
({"category_name": "Vegetables"}))
else:
return render_template("veg.html", count_veg_tasks=count_veg_tasks,
page_title="Vegetable Recipes",
tasks=mongo.db.tasks.find
({"category_name": "Vegetables"}))
@app.route('/grains', methods=['GET'])
def grains():
count_grains_tasks = mongo.db.tasks.find({"category_name": "Grains"}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('grains.html',
count_grains_tasks=count_grains_tasks,
page_title='Grains Recipes',
current_user=current_user,
tasks=mongo.db.tasks.find
({"category_name": "Grains"}))
else:
return render_template('grains.html',
count_grains_tasks=count_grains_tasks,
page_title="Grains Recipes",
tasks=mongo.db.tasks.find
({"category_name": "Grains"}))
@app.route('/pasta', methods=['GET'])
def pasta():
count_pasta_tasks = mongo.db.tasks.find({"category_name": "Pasta"}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('pasta.html',
count_pasta_tasks=count_pasta_tasks,
page_title='Pasta Recipes',
current_user=current_user,
tasks=mongo.db.tasks.find
({"category_name": "Pasta"}))
else:
return render_template("pasta.html",
count_pasta_tasks=count_pasta_tasks,
page_title="Pasta Recipes",
tasks=mongo.db.tasks.find
({"category_name": "Pasta"}))
@app.route('/task/<tasks_id>', methods=['GET', 'POST'])
def task(tasks_id):
count_tasks = mongo.db.tasks.find().count()
favourite_count = mongo.db.tasks.find({'favourite': True}).count()
"""
Route for viewing a single recipe in detail.
"""
a_recipe = mongo.db.tasks.find_one_or_404({"_id": ObjectId(tasks_id)})
if 'logged_in' in session:
current_user = mongo.db.user.find_one({
'name': session['username'].title()})
return render_template('recipe.html',
count_tasks=count_tasks,
favourite_count=favourite_count,
task=a_recipe, current_user=current_user,
title=a_recipe['recipe_name'])
else:
return render_template('recipe.html', count_tasks=count_tasks,
favourite_count=favourite_count,
task=a_recipe, title=a_recipe['recipe_name'])
@app.route('/add_task', methods=['GET', 'POST'])
def add_tasks():
"""
Add a new recipe to mongodb database collection
"""
count_tasks = mongo.db.tasks.find().count()
favourite_count = mongo.db.tasks.find({'favourite': True}).count()
# Allows task categories in MongoDB to connect with addtask.html file
if 'logged_in' not in session: # Check for user logged in
flash('Apologies, only logged in users can add recipes.')
return redirect(url_for('index'))
form = RecipeForm(request.form) # Initialise the form
user = mongo.db.user.find_one({"name": session['username'].title()})
if 'logged_in' in session:
form = RecipeForm(request.form)
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
else:
return render_template('addrecipe.html', count_tasks=count_tasks,
favourite_count=favourite_count,
page_title='Add New Recipe', form=form,
current_user=current_user)
if form.validate_on_submit(): # Insert new recipe if form is submitted
tasks = mongo.db.tasks
tasks.insert_one({
'category_name': request.form['category_name'],
'complexity': request.form['complexity'],
'recipe_name': request.form['recipe_name'],
'author_name': request.form['author_name'],
'prep_time_mins': int(request.form['prep_time_mins']),
'cook_time_mins': int(request.form['cook_time_mins']),
'calories': int(request.form['calories']),
'servings': int(request.form['servings']),
'brief_description': request.form['brief_description'],
'ingredients': request.form['ingredients'],
'instructions': request.form['instructions'],
'recipe_image': request.form['recipe_image'],
'favourite': 'favourite' in request.form,
'username': session['username'].title(),
'created_by': {
'_id': user['_id'],
'name': user['name']}})
return redirect(url_for('index'))
return render_template('addrecipe.html', count_tasks=count_tasks,
favourite_count=favourite_count,
current_user=current_user,
form=form, title="Add New Recipe")
@app.route('/edit_task/<task_id>', methods=['GET', 'POST'])
def edit_task(task_id):
count_tasks = mongo.db.tasks.find().count()
favourite_count = mongo.db.tasks.find({'favourite': True}).count()
if 'logged_in' not in session: # Check if its a logged in user
flash('Apologies, only logged in users can edit recipes.')
return redirect(url_for('index'))
user = mongo.db.user.find_one({"name": session['username'].title()})
task = mongo.db.tasks.find_one_or_404({"_id": ObjectId(task_id)})
form = RecipeForm()
"""
Find a particular task, parameter passed is 'id', looking
for a match to 'id' in MongoDB, then wrapped for editing
purposes.
Reuse much of the layout in 'add_tasks' function,
but with pre-populated fields.
"""
if user['name'].title() == task['username'].title():
if request.method == 'GET':
form = RecipeForm(data=task)
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
return render_template('editrecipe.html', task=task,
current_user=current_user,
count_tasks=count_tasks,
favourite_count=favourite_count,
form=form, title="Edit Recipe")
if form.validate_on_submit():
tasks = mongo.db.tasks # Access to the tasks collection in mongo.db
tasks.update_one({
'_id': ObjectId(task_id),
}, {
'$set': {
'category_name': request.form['category_name'],
'complexity': request.form['complexity'],
'recipe_name': request.form['recipe_name'],
'author_name': request.form['author_name'],
'prep_time_mins': int(request.form['prep_time_mins']),
'cook_time_mins': int(request.form['cook_time_mins']),
'calories': int(request.form['calories']),
'servings': int(request.form['servings']),
'brief_description': request.form['brief_description'],
'ingredients': request.form['ingredients'],
'instructions': request.form['instructions'],
'recipe_image': request.form['recipe_image'],
'favourite': 'favourite' in request.form
}})
flash('Your recipe has been updated!')
return redirect(url_for('task', tasks_id=task_id))
flash("Apologies, this is not your recipe to edit!")
return redirect(url_for('task', tasks_id=task_id))
@app.route('/delete_task/<task_id>')
def delete_task(task_id):
"""
We access the tasks collection & call to delete selected task.
"""
if session:
user = mongo.db.user.find_one({"name": session['username'].title()})
task = mongo.db.tasks.find_one_or_404({'_id': ObjectId(task_id)})
if user['name'].title() == task['username'].title():
tasks = mongo.db.tasks
tasks.delete_one({
'_id': ObjectId(task_id)
})
return redirect(url_for('index'))
flash("Apologies, this is not your recipe to edit!")
return redirect(url_for('task', tasks_id=task_id))
else:
flash('Apologies, logged in users can only view this page')
return redirect(url_for('index'))
@app.route('/count_tasks') # Enables the total recipe counter
def count_tasks():
count_tasks = mongo.db.tasks.find().count()
return render_template("index.html",
count_tasks=count_tasks)
@app.route('/favourite_count') # Enables the favourite recipe counter
def favourite_count():
favourite_count = mongo.db.tasks.find({'favourite': True}).count()
return render_template("index.html",
favourite_count=favourite_count)
@app.errorhandler(404)
# 404 error message supports user when Virtual Cookbook incorrectly renders
def page_not_found(e):
"""Route for handling 404 errors"""
return render_template('404.html',
title="Page Not Found!"), 404
@app.route('/profile/<user_id>')
def profile_page(user_id): # User profile page
count_tasks = mongo.db.tasks.find().count()
favourite_count = mongo.db.tasks.find({'favourite': True}).count()
if 'logged_in' not in session: # Check if its a logged in user
flash('Apologies, this profile page viewed by logged in users only.')
return redirect(url_for('index'))
current_user = mongo.db.user.find_one({"_id": ObjectId(user_id)})
task = mongo.db.tasks.find({
'username': current_user['name']}).sort('_id', pymongo.ASCENDING)
count = mongo.db.tasks.find({'username': current_user['name']}).count()
return render_template('profile.html',
current_user=current_user, count_tasks=count_tasks,
favourite_count=favourite_count,
tasks=task, count=count, title="Profile Page")
@app.route('/register', methods=['GET', 'POST'])
def register():
"""Function for handling the registration of users"""
if 'logged_in' in session: # Check is user already logged in
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = mongo.db.user
dup_user = user.find_one({'name': request.form['username'].title()})
if dup_user is None:
hash_pass = generate_password_hash(request.form['password'])
user.insert_one({'name': request.form['username'].title(),
'pass': hash_pass})
session['username'] = request.form['username']
session['logged_in'] = True
return redirect(url_for('index'))
flash('Attention: This username is already taken. Please try another.')
return redirect(url_for('register'))
return render_template('register.html', form=form, title="Register")
@app.route('/login', methods=['GET', 'POST'])
def user_login():
"""Function for User login to Virtual Cookbook"""
if 'logged_in' in session: # Check is already logged in
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = mongo.db.user
logged_in_user = user.find_one({
'name': request.form['username'].title()})
if logged_in_user:
if check_password_hash(logged_in_user['pass'],
request.form['password']):
session['username'] = request.form['username']
session['logged_in'] = True
return redirect(url_for('index'))
flash('Attention: Password is incorrect. Please try again.')
return redirect(url_for('user_login'))
return render_template('login.html', form=form, title='Login')
@ app.route('/search', methods=["GET", "POST"])
def search():
query = request.form.get("query")
results = mongo.db.tasks.find({'$text': {'$search': str(query)}}).limit(20)
result_count = mongo.db.tasks.find({'$text': {'$search': query}}).count()
if 'logged_in' in session:
current_user = mongo.db.user.find_one({'name': session[
'username'].title()})
if result_count > 0:
return render_template(
"search.html", results=results, query=query,
current_user = current_user,
page_title="Search Results", result_count=result_count)
if result_count == 0:
return render_template(
"search.html", results=results, query=query,
current_user = current_user,
page_title="Search Results", result_count=result_count)
if result_count == 1:
return render_template(
"search.html", results=results, query=query,
current_user = current_user,
page_title="Search Results", result_count=result_count)
else:
return render_template(
"search.html", results=results, query=query,
page_title="Search Results", result_count=result_count)
@app.route('/logout')
def logout():
"""Logs the user out and redirects to home"""
session.clear() # End the session
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(host=os.environ.get('IP', "0.0.0.0"),
port=int(os.environ.get('PORT', "5000")),
debug=False)