-
Notifications
You must be signed in to change notification settings - Fork 0
/
grub.py
526 lines (490 loc) · 22.6 KB
/
grub.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import sys; sys.path.insert(0, 'lib') # this line is necessary for the rest
import os # of the imports to work!
import web
from jinja2 import Environment, FileSystemLoader
from datetime import datetime
import sqlitedb
from sets import Set
from fractions import gcd
urls = (
'/hello', 'hello', '/view', 'view', '/user', 'user', '/cookbook', 'cookbook', '/search', 'search', '/upload_page', 'upload_page', '/search_users', 'search_users', '/login', 'login', '/logout', 'logout', '/createAccount', 'createAccount',
)
web.config.debug = False
app = web.application(urls, locals())
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'user': None})
render = web.template.render('templates/')
class hello:
def GET(self):
if session.user == None:
return render_template('login.html')
all_recipes = sqlitedb.getAllRecipes()
r_photos = sqlitedb.getRecommendedPhotos()
recommended_photos = []
for r in r_photos:
recommended_photos.append(r['Photo'])
fp = sqlitedb.getFeaturedRecipe()
featured_recipe_photo = []
featured_recipe_photo.append(fp['Photo'])
featured_recipe = sqlitedb.getRecipe(1)
recommended_recipes = sqlitedb.getRecommendedRecipes(session.user)
social_feed = sqlitedb.getSocialFeed()
if social_feed:
print "printing social feed"
print social_feed
return render_template('curr_time.html', all_recipes = all_recipes, recommended_photos = recommended_photos, featured_recipe_photo = featured_recipe_photo, recommended_recipes = recommended_recipes, user = session.user, social_feed = social_feed, featured_recipe = featured_recipe)
class view:
def GET(self):
if session.user == None:
return render_template('login.html')
post_params = web.input()
editAbout = False
if 'editAboutMe' in post_params:
editAbout = True
if 'newAboutMe' in post_params:
editAbout = False
sqlitedb.updateAboutMe(userID, post_params['newAboutMe'])
recipeID = 0
if 'recipeID' in post_params:
recipeID = post_params['recipeID']
recipe = sqlitedb.getRecipe(recipeID)
instructions = sqlitedb.getInstructions(recipeID)
ingredients = sqlitedb.getIngredients(recipeID)
tags = sqlitedb.getTags(recipeID)
photos = sqlitedb.getPhotos(recipeID)
categories = sqlitedb.getCategories(recipeID)
reviews = sqlitedb.getReviews(recipeID)
userVotes = {0 : 'na'}
for review in reviews:
userVotes[review['ReviewID']] = sqlitedb.userVoted(review['ReviewID'], session.user)
userHasReviewed = sqlitedb.hasUserReviewed(recipeID, session.user)
cookbooks = sqlitedb.getCookbooks(session.user)
userMatchesRecipeAuthor = False
for result in recipe:
if session.user == result['UserID']:
userMatchesRecipeAuthor = True
return render_template('view_recipe.html', recipe = recipe, recipeID = recipeID, instructions = instructions, ingredients = ingredients, tags = tags, photos = photos, categories = categories, reviews = reviews, cookbooks = cookbooks, currentUser = session.user, userHasReviewed = userHasReviewed, userMatchesRecipeAuthor = userMatchesRecipeAuthor, userVotes = userVotes, editAbout = editAbout)
#added by valerie for reviews
def POST(self):
post_params = web.input()
editAbout = False
recipeID = post_params['recipeID']
print post_params
if 'editAboutMe' in post_params:
editAbout = True
if 'newAboutMe' in post_params:
editAbout = False
sqlitedb.updateRecipeReview(post_params['reviewID'], post_params['newAboutMe'], int(post_params['stars']))
#calculate new ratings
ratings = sqlitedb.getReviews(recipeID)
counter = 0.0
total = 0
for r in ratings:
total += r['Rating']
counter += 1.0
new_rating = total/counter
new_rating = format(new_rating, '.2f')
sqlitedb.updateRating(recipeID, new_rating)
if 'review' in post_params:
reviewID = sqlitedb.assignReviewID()
sqlitedb.addRecipeReview(reviewID, recipeID, session.user, post_params['review'], int(post_params['stars']), 0, 0)
#need to update overall rating now
ratings = sqlitedb.getReviews(recipeID)
counter = 0.0
total = 0
for r in ratings:
total += r['Rating']
counter += 1.0
new_rating = total/counter
new_rating = format(new_rating, '.2f')
sqlitedb.updateRating(recipeID, new_rating)
if 'added_cookbookID' in post_params:
sqlitedb.addCookbookRecipe(recipeID, post_params['added_cookbookID'])
if 'd' in post_params:
sqlitedb.deleteReview(post_params['DeleteReview'])
#need to update overall rating now
ratings = sqlitedb.getReviews(recipeID)
counter = 0.0
total = 0
for r in ratings:
total += r['Rating']
counter += 1.0
new_rating = total/counter
new_rating = format(new_rating, '.2f')
sqlitedb.updateRating(recipeID, new_rating)
if 'HelpfulReview' in post_params:
reviewID = post_params['reviewID']
sqlitedb.addOneThumbsUp(reviewID, session.user)
sqlitedb.updateVoteReviewStatus(reviewID, session.user, "up")
if 'UnhelpfulReview' in post_params:
reviewID = post_params['reviewID']
sqlitedb.addOneThumbsDown(reviewID, session.user)
sqlitedb.updateVoteReviewStatus(reviewID, session.user, "down")
#reload page info
recipe = sqlitedb.getRecipe(recipeID)
instructions = sqlitedb.getInstructions(recipeID)
ingredients = sqlitedb.getIngredients(recipeID)
tags = sqlitedb.getTags(recipeID)
photos = sqlitedb.getPhotos(recipeID)
categories = sqlitedb.getCategories(recipeID)
reviews = sqlitedb.getReviews(recipeID)
userVotes = {0 : 'na'}
for review in reviews:
userVotes[review['ReviewID']] = sqlitedb.userVoted(review['ReviewID'], session.user)
print userVotes
userHasReviewed = sqlitedb.hasUserReviewed(recipeID, session.user)
cookbooks = sqlitedb.getCookbooks(session.user)
userMatchesRecipeAuthor = False
for result in recipe:
if session.user == result['UserID']:
userMatchesRecipeAuthor = True
return render_template('view_recipe.html', recipe = recipe, instructions = instructions, ingredients = ingredients, tags = tags, photos = photos, categories = categories, reviews = reviews, cookbooks = cookbooks, recipeID = recipeID, currentUser = session.user, userHasReviewed = userHasReviewed, userMatchesRecipeAuthor = userMatchesRecipeAuthor, userVotes = userVotes, editAbout = editAbout)
class user:
def GET(self):
if session.user == None:
return render_template('login.html')
post_params = web.input()
userID = None
userRecipes = None
userAboutMe = None
userFollowers = None
userFollowing = None
userCookbooks = None
viewingOwnProfile = False
editAbout = False
follower = False
recipes = []
recipe_photos = []
currentUser = session.user
if 'userID' in post_params:
userID = post_params['userID']
if userID == session.user:
viewingOwnProfile = True
elif session.user:
userID = session.user
viewingOwnProfile = True
else:
return render_template('login.html')
if 'editAboutMe' in post_params:
editAbout = True
if 'newAboutMe' in post_params:
editAbout = False
sqlitedb.updateAboutMe(userID, post_params['newAboutMe'])
following = sqlitedb.getFollowing(currentUser)
for r in following:
print r['UserID']
if r['UserID'] == userID:
follower = True
userRecipes = sqlitedb.getUserRecipes(userID)
for recipe in userRecipes:
recipes.append(recipe['RecipeID'])
if len(recipes) > 0:
all_photos = sqlitedb.getRecipePhotos(recipes)
for r in all_photos:
recipe_photos.append(r['Photo'])
userAboutMe = sqlitedb.getAboutMe(userID)
userFollowers = sqlitedb.getFollowers(userID)
userFollowing = sqlitedb.getFollowing(userID)
userCookbooks = sqlitedb.getCookbooks(userID)
if 'unfollowing' in post_params:
sqlitedb.unfollow(session.user, post_params['unfollowing'])
print recipe_photos
return render_template('view_user.html', userID = userID, userRecipes = userRecipes, userAboutMe = userAboutMe, userFollowers = userFollowers, userFollowing = userFollowing, userCookbooks = userCookbooks, viewingOwnProfile = viewingOwnProfile, currentUser = currentUser, editAbout = editAbout, follower = follower, recipe_photos = recipe_photos)
def POST(self):
post_params = web.input()
cookbookID = None
currentUser = session.user
editAbout = False
viewingOwnProfile = False
recipe_photos = []
recipes = []
if 'userID' in post_params:
userID = post_params['userID']
if userID == session.user:
viewingOwnProfile = True
elif session.user:
userID = session.user
viewingOwnProfile = True
else:
return render_template('login.html')
if 'editAboutMe' in post_params:
editAbout = True
if 'newAboutMe' in post_params:
editAbout = False
sqlitedb.updateAboutMe(userID, post_params['newAboutMe'])
if 'deleteCookbook' in post_params:
sqlitedb.deleteCookbook(post_params['deleteCookbook'])
if 'cookbook' in post_params:
cookbookID = sqlitedb.assignCookbookID()
sqlitedb.addCookbook(cookbookID, session.user, post_params['cookbook'])
if 'deleteRecipe' in post_params:
recipeID = post_params['deleteRecipe']
sqlitedb.deleteRecipe(recipeID)
currentUser = session.user
if 'userID' in post_params:
userID = post_params['userID']
userRecipes = sqlitedb.getUserRecipes(userID)
for recipe in userRecipes:
recipes.append(recipe['RecipeID'])
if len(recipes) > 0:
all_photos = sqlitedb.getRecipePhotos(recipes)
for r in all_photos:
recipe_photos.append(r['Photo'])
userAboutMe = sqlitedb.getAboutMe(userID)
userFollowers = sqlitedb.getFollowers(userID)
userFollowing = sqlitedb.getFollowing(userID)
userCookbooks = sqlitedb.getCookbooks(userID)
if 'unfollowing' in post_params:
sqlitedb.unfollow(session.user, post_params['unfollowing'])
if 'addFollower' in post_params:
sqlitedb.addFollower(post_params['addFollower'], session.user)
return render_template('view_user.html', userID = userID, userRecipes = userRecipes, userAboutMe = userAboutMe, userFollowers = userFollowers, userFollowing = userFollowing, userCookbooks = userCookbooks, viewingOwnProfile=viewingOwnProfile, currentUser = currentUser, editAbout = editAbout, recipe_photos = recipe_photos)
class cookbook:
# THIS IS NOT COMPLETE YET - 1/31 at 4:28pm
#Edit: 2/7, Valerie will now try to complete it
def GET(self):
if session.user == None:
return render_template('login.html')
post_params = web.input()
cookbookID = None
cookbookRecipes = None
cookbookInfo = None
recipes = []
all_photos = None
all_recipes = None
cookbookInfo = None
recipe_photos = []
if 'cookbookID' in post_params:
cookbookID = post_params['cookbookID']
cookbookRecipes = sqlitedb.getCookbooks_recipes(cookbookID)
for recipe in cookbookRecipes:
recipes.append(recipe['RecipeID'])
if len(recipes) > 0:
all_photos = sqlitedb.getRecipePhotos(recipes)
all_recipes = sqlitedb.getRecipes(recipes)
for r in all_photos:
recipe_photos.append(r['Photo'])
cookbookInfo = sqlitedb.getCookbookInfo(cookbookID)
return render_template('view_cookbook.html', cookbookID = cookbookID, cookbookInfo = cookbookInfo, cookbookRecipes = cookbookRecipes, all_photos = all_photos, all_recipes = all_recipes, currentUser = session.user, recipe_photos = recipe_photos)
def POST(self):
if session.user == None:
return render_template('login.html')
post_params = web.input()
cookbookID = None
cookbookRecipes = None
cookbookInfo = None
recipes = []
recipe_photos = []
all_photos = None
all_recipes = None
cookbookInfo = None
recipeID = None
if 'recipeID' in post_params:
recipeID = post_params['recipeID']
cookbookID = post_params['cookbookID']
sqlitedb.removeRecipeFromCookbook(cookbookID, recipeID)
if 'cookbookID' in post_params:
cookbookID = post_params['cookbookID']
cookbookRecipes = sqlitedb.getCookbooks_recipes(cookbookID)
for recipe in cookbookRecipes:
recipes.append(recipe['RecipeID'])
if len(recipes) > 0:
all_photos = sqlitedb.getRecipePhotos(recipes)
all_recipes = sqlitedb.getRecipes(recipes)
for r in all_photos:
recipe_photos.append(r['Photo'])
cookbookInfo = sqlitedb.getCookbookInfo(cookbookID)
return render_template('view_cookbook.html', cookbookID = cookbookID, cookbookInfo = cookbookInfo, cookbookRecipes = cookbookRecipes, all_photos = all_photos, all_recipes = all_recipes, currentUser = session.user, recipe_photos = recipe_photos)
class search:
def GET(self):
if session.user == None:
return render_template('login.html')
return render_template('search_recipes.html')
def POST(self):
post_params = web.input()
recipeID = ""
userID = post_params['userID']
recipeName = post_params['recipeName']
completionTime = post_params['completionTime']
ingredients = post_params['ingredients'].split()
categories = []
if 'categoriesBR' in post_params:
categories.append("breakfast")
if 'categoriesLU' in post_params:
categories.append("lunch")
if 'categoriesDI' in post_params:
categories.append("dinner")
if 'categoriesSA' in post_params:
categories.append("savory")
if 'categoriesSW' in post_params:
categories.append("sweet")
if 'categoriesVE' in post_params:
categories.append("vegetarian")
if 'categoriesGF' in post_params:
categories.append("gluten free")
tags = post_params['tags'].split()
final_search_results = sqlitedb.searchRecipes(recipeID, userID, recipeName, completionTime, ingredients, categories, tags)
recipe_photos = []
for result in final_search_results:
photo = sqlitedb.getPhotos(result['RecipeID'])[0]['Photo']
print photo
recipe_photos.append(photo)
return render_template('search_recipes.html', search_results = final_search_results, recipe_photos = recipe_photos)
class login:
def GET(self):
return render_template('login.html')
def POST(self):
post_params = web.input()
userIDInput = post_params['userID']
passwordInput = post_params['password']
actualPasswordResult = sqlitedb.getPassword(userIDInput)
if len(actualPasswordResult) == 0:
return render_template('login.html', message = "Username " + userIDInput + " does not exist.")
else:
actualPassword = actualPasswordResult[0]['Password']
if passwordInput == actualPassword:
session.user = userIDInput
return web.redirect('/hello')
else:
return render_template('login.html', message = "Please enter the correct password.")
class logout:
def GET(self):
session.kill()
session.user = None
return web.redirect('/login')
def POST(self):
session.kill()
session.user = None
return web.redirect('/login')
class search_users:
def GET(self):
if session.user == None:
return render_template('login.html')
return render_template('search_users.html')
def POST(self):
post_params = web.input()
userID = post_params['userID']
search_results = sqlitedb.searchUsers(userID)
return render_template('search_users.html', search_results = search_results)
#adam's stuff
class upload_page:
def GET(self):
if session.user == None:
return render_template('login.html')
return render_template('upload_page.html', currentUser = session.user)
def POST(self):
recipeID = sqlitedb.assignRecipeID()
data = web.input()
sqlitedb.addRecipe(recipeID,
session.user, #TODO: ADD THE USER ID
0,
data.name,
data.description,
data.time,
data.servings,
data.spicy,
data.diff)
tags = data.tags
tags = tags.split()
for tag in tags:
sqlitedb.addRecipeTags(recipeID, tag)
numIngredients = int(data.numIngredients)
for i in range(numIngredients):
ingredient = data["ingredientIngredient" + str(i)]
unit = "none"
if ("ingredientUnit" + str(i)) in data:
unit = data["ingredientUnit" + str(i)]
numerator = 1
denominator = 1
if ("ingredientQuantity" + str(i)) in data:
quantity = data["ingredientQuantity" + str(i)]
if '/' in quantity:
quantityFraction = quantity.split('/')
numerator = int(quantityFraction[0])
denominator = int(quantityFraction[0])
elif '.' in quantity:
quantityDecimal = float(quantity)
while (quantityDecimal % 1) != 0:
quantityDecimal *= 10
denominator *= 10
numerator = int(quantityDecimal)
factor = gcd(numerator, denominator)
numerator /= factor
denominator /= factor
elif quantity != "":
numerator = int(quantity)
sqlitedb.addRecipeIngredients(recipeID, ingredient, numerator, denominator, unit)
numInstructions = int(data.numInstructions)
for i in range(numInstructions):
if ("instruction" + str(i)) in data:
sqlitedb.addRecipeInstruction(recipeID, i + 1, data["instruction" + str(i)])
sqlitedb.addRecipePhotos(recipeID, data.image)
print data
if 'categoriesBR' in data:
sqlitedb.addRecipeCategories(recipeID, "breakfast")
if 'categoriesLU' in data:
sqlitedb.addRecipeCategories(recipeID, "lunch")
if 'categoriesDI' in data:
sqlitedb.addRecipeCategories(recipeID, "dinner")
if 'categoriesSA' in data:
sqlitedb.addRecipeCategories(recipeID, "savory")
if 'categoriesSW' in data:
sqlitedb.addRecipeCategories(recipeID, "sweet")
if 'categoriesVE' in data:
sqlitedb.addRecipeCategories(recipeID, "vegetarian")
if 'categoriesGF' in data:
sqlitedb.addRecipeCategories(recipeID, "gluten free")
recipe = sqlitedb.getRecipe(recipeID)
instructions = sqlitedb.getInstructions(recipeID)
ingredients = sqlitedb.getIngredients(recipeID)
tags = sqlitedb.getTags(recipeID)
photos = sqlitedb.getPhotos(recipeID)
categories = sqlitedb.getCategories(recipeID)
reviews = sqlitedb.getReviews(recipeID)
return render_template('view_recipe.html', recipe = recipe, instructions = instructions, ingredients = ingredients, tags = tags, photos = photos, categories = categories, reviews = reviews)
class createAccount:
def GET(self):
return render_template('create_account.html')
def POST(self):
post_params = web.input()
username = post_params['userID']
password = post_params['password']
confirmPassword = post_params['confirmPassword']
if username == "":
return render_template('create_account.html', message = "Please enter a non-empty username")
if password == "":
return render_template('create_account.html', message = "Please enter a non-empty password")
if password != confirmPassword:
return render_template('create_account.html', message = "Password does not match Confirm Password!")
usernameExistCheck = sqlitedb.getPassword(username)
if len(usernameExistCheck) != 0:
message = "Username '"
message = message + username
message = message + "' already exists. Please choose a different username!"
return render_template('create_account.html', message = message)
else:
sqlitedb.addUser(username, password)
sqlitedb.addAboutMe(username, "Currently no about me.")
session.user = username
return web.redirect('/hello')
# helper method to render a template in the templates/ directory
#
# `template_name': name of template file to render
#
# `**context': a dictionary of variable names mapped to values
# that is passed to Jinja2's templating engine
#
# See curr_time's `GET' method for sample usage
#
# WARNING: DO NOT CHANGE THIS METHOD
def render_template(template_name, **context):
extensions = context.pop('extensions', [])
globals = context.pop('globals', {})
jinja_env = Environment(autoescape=True,
loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),
extensions=extensions,
)
jinja_env.globals.update(globals)
web.header('Content-Type','text/html; charset=utf-8', unique=True)
return jinja_env.get_template(template_name).render(context)
if __name__ == "__main__":
app.run()