-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrud.py
executable file
·450 lines (318 loc) · 12.6 KB
/
crud.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
"""CRUD operations.
recipe 1 id: 08Ifren64xtMVpoG03Qx
recipe 2 id: 08OniGKxjkMtCTb7tX7d
"""
from model import db, User, Recipe, Tag, Ingredient, RecipeTag, UserRecipe, connect_to_db
from random import sample
from sqlalchemy import func, desc #need for count - popular recipes
# CREATE USER, TAG, RECIPE, INGREDIENT
def create_user(fname, lname, phone, password_hash):
"""Create and return user."""
user = User(fname=fname,
lname=lname,
phone=phone,
password_hash=password_hash)
db.session.add(user)
db.session.commit()
return user
def update_user(user_id, fname=None, lname=None, new_phone=None):
"""Update user and return user.
>>> update_user(1, "Rachel", "Perkins Updated!", 4084256597)
<User id=1,
name=Rach Perkins Updated!,
phone=4079638488>
"""
user = db.session.query(User).get(user_id)
if fname:
user.fname = fname
if lname:
user.lname = lname
if new_phone:
user.phone = new_phone
db.session.commit()
return user
def update_password(user_id, new_password_hash):
"""Update password and return user."""
user = db.session.query(User).get(user_id)
user.password_hash = new_password_hash
db.session.commit()
return user
def delete_user(user_id):
"""Delete user permanently."""
user = db.session.query(User).get(user_id)
db.session.delete(user)
db.session.commit()
return f'User {user_id} is deleted.'
def create_tag(name, tag_id):
"""Create and return tag."""
tag = Tag(name=name,
tag_id=tag_id)
db.session.add(tag)
db.session.commit()
return tag
def create_recipe(img, serves, title, directions, cookingTime, prepTime, recipe_id):
"""Create and return recipe."""
recipe = Recipe(img=img,
# tags_full=tags_full,
# ingredients_full=ingredients_full,
serves=serves, #tagIds=tagIds,
title=title,
directions=directions,
cookingTime=cookingTime,
prepTime=prepTime,
recipe_id=recipe_id)
db.session.add(recipe)
db.session.commit()
return recipe
def create_ingredient(recipe_id, detailed_ingredient, abridged_ingredient):
"""Create and return recipe."""
ingredient_added = Ingredient(
recipe_id=recipe_id,
detailed_ingredient=detailed_ingredient,
abridged_ingredient=abridged_ingredient
)
db.session.add(ingredient_added)
db.session.commit()
return ingredient_added
# CREATE RELATIONSHIP TABLE
def create_recipe_tag_relationship(recipe_id, tag_id):
"""Create and return a recipe/tag association."""
recipe_tag = RecipeTag(recipe_id=recipe_id, tag_id=tag_id)
db.session.add(recipe_tag)
db.session.commit()
# THIS WILL BE WORKED ON LATER WHEN USERS CAN UPDATE
def create_user_recipe(user_id, recipe_id):
"""Create and return a new recipe for individual user."""
user_recipe = UserRecipe(user_id=user_id, recipe_id=recipe_id)
db.session.add(user_recipe)
db.session.commit()
return user_recipe
def delete_user_recipe(user_id, recipe_id):
"""Given user_id and recipe_id, deletes relationship from database."""
unwanted_recipe = UserRecipe.query.filter(UserRecipe.user_id == user_id, UserRecipe.recipe_id == recipe_id).one()
print(unwanted_recipe)
db.session.delete(unwanted_recipe)
db.session.commit()
if (UserRecipe.query.filter(UserRecipe.user_id == user_id, UserRecipe.recipe_id == recipe_id).one()):
unwanted_recipe = UserRecipe.query.filter(UserRecipe.user_id == user_id, UserRecipe.recipe_id == recipe_id).one()
db.session.delete(recipe)
db.session.commit()
return None
# TEST FUNCTION TO POPULATE DATA (RECIPES, USERS, TAGS)
def test_every_table():
test_user = create_user('Bixby', 'Perkins', '[email protected]', 'test')
test_recipe = create_recipe('/img.jpg', '4', 'Bixby Biscuits',
'Cook biscuits according to package directions. Remove soy chorizo from casing. In a large skillet over medium heat, add soy chorizo, breaking it up into pieces as it cooks, about 8-10 minutes. When soy chorizo reaches 165ºF, reduce heat to medium. Add salsa and stir to combine. Add almond milk to pan and cook for 5-7 minutes as gravy thickens, stirring occasionally. Remove from heat.\nTo serve, break open 2 biscuits in a shallow serving dish and top with 1/4 of gravy and green chiles, if using. Repeat with remaining biscuits',
'2 hours', '1 hour', 'bixbyid')
test_tag = create_tag('Not So Yummy', 999)
print(test_user)
print(test_recipe)
print(test_tag)
def search_recipes(search_phrase):
"""Searches recipes based on the input phrase and returns recipe ids as set."""
related_recipes_id = set()
search = "%{}%".format(search_phrase).lower()
tag_results = Tag.query.filter(Tag.name.ilike(search)).all()
# print("Tag Results", tag_results)
for tag in tag_results:
tag_recipes = get_recipe_ids_by_tag_id(tag.tag_id)
for recipe in tag_recipes:
related_recipes_id.add(recipe)
# print("These are all the related recipe ids:", related_recipes_id)
ingredients_results = Ingredient.query.filter(Ingredient.detailed_ingredient.ilike(search)).all()
# print("Ingredients Results", ingredients_results)
for ingredient in ingredients_results:
related_recipes_id.add(ingredient.recipe_id)
# print("These are all the searches including ingredients as well!", related_recipes_id)
title_results = Recipe.query.filter(Recipe.title.ilike(search)).all()
# print("Recipe Title Results", title_results)
for recipe in title_results:
related_recipes_id.add(recipe.recipe_id)
print("These are all the searches including Title results as well!", related_recipes_id)
return related_recipes_id
def get_recipes(limit=24):
"""Return not random recipes. Default 24."""
return Recipe.query.limit(limit).all()
def get_random_recipes(limit=24):
"""Return random recipes. Default 24."""
return sample(Recipe.query.all(), limit)
def get_recipe_by_id(recipe_id):
"""Return one recipe."""
return Recipe.query.filter_by(recipe_id=recipe_id).one()
def get_tags():
"""Return all tags."""
return Tag.query.all()
def get_tag_name(tag_id):
"""Return tag name."""
return Tag.query.filter(Tag.tag_id == tag_id).one()
def get_users():
"""Return all users."""
return User.query.all()
def get_user_by_phone(phone):
"""Return a user by phone."""
return User.query.filter(User.phone == phone).first()
def get_user_by_id(user_id):
"""Return a user by user ID."""
return User.query.filter(User.user_id == user_id).first()
def get_tags_info_by_recipe_id(recipe_id):
"""Return multiple tags.
>>> get_tags_info_by_recipe_id('08Ifren64xtMVpoG03Qx')
[
<RecipeTag recipetag_id=1,
recipe_id=1
tag_id=10>
,
<RecipeTag recipetag_id=2,
recipe_id=2
tag_id=47>
]
"""
recipe_tag_id_only = RecipeTag.query.filter(RecipeTag.recipe_id == recipe_id).all()
all_recipe_tag_info = []
for tag in recipe_tag_id_only:
tag_info = Tag.query.filter(Tag.tag_id == tag.tag_id).one()
all_recipe_tag_info.append(tag_info)
return all_recipe_tag_info
def get_user_recipes_data(user_id):
"""Given a user_id input, return all the recipes that they have favorited.
>>> get_user_recipes_data(1)
[
<Userrecipe user_recipe_id=1
user_id=1,
recipe_id=MWL6CyjVxqoOnYVH55eQ>
,
<Userrecipe user_recipe_id=2
user_id=1,
recipe_id=3YiI1WbzAzaj7J4GFbkF>
]
"""
user_favorites = UserRecipe.query.filter(UserRecipe.user_id == user_id).all()
all_user_favorites = []
for recipe in user_favorites:
recipe_info = Recipe.query.filter(Recipe.recipe_id == recipe.recipe_id).one()
all_user_favorites.append(recipe_info)
return all_user_favorites
def get_favorite_boolean(user_id, recipe_id):
"""Given a user_id input, return all the recipes that they have favorited.
>>> get_favorite_boolean(1, 'MWL6CyjVxqoOnYVH55eQ')
True
"""
query = UserRecipe.query.filter(UserRecipe.user_id == user_id, UserRecipe.recipe_id == recipe_id).first()
return query is not None
def get_popular_recipes(limit=12):
"""Returns the most popular recipes in descending order."""
most_popular = db.session.query(UserRecipe.recipe_id, func.count(UserRecipe.recipe_id).label('qty')).group_by(UserRecipe.recipe_id).order_by(desc('qty')).limit(limit)
most_popular_recipes = []
for recipe in most_popular:
recipe_info = Recipe.query.filter(Recipe.recipe_id == recipe.recipe_id).one()
most_popular_recipes.append(recipe_info)
return most_popular_recipes
def get_tag_names_by_recipe_id(recipe_id):
"""Return multiple tags.
>>> get_tag_names_by_recipe_id('08Ifren64xtMVpoG03Qx')
[
<RecipeTag recipetag_id=1,
recipe_id=1
tag_id=10>
,
<RecipeTag recipetag_id=2,
recipe_id=2
tag_id=47>
]
"""
#THIS IS WEIRD TO DO TWO QUERIES NO?
response = RecipeTag.query.filter(RecipeTag.recipe_id == recipe_id).all()
recipe_tags_names = []
for item in response:
tag = Tag.query.filter(Tag.tag_id == item.tag_id).one()
recipe_tags_names.append(tag.name)
return recipe_tags_names
def get_recipe_ids_by_tag_id(tag_id):
"""Return multiple recipes.
>>> get_recipe_id_by_tag_id(104)
[
<RecipeTag recipetag_id=1,
recipe_id=1
tag_id=10>
,
<RecipeTag recipetag_id=2,
recipe_id=2
tag_id=47>
]
"""
#THIS IS WEIRD TO DO TWO QUERIES NO?
response = RecipeTag.query.filter(RecipeTag.tag_id == tag_id).all()
recipe_ids_list = []
for item in response:
recipe_id_append = Recipe.query.filter(Recipe.recipe_id == item.recipe_id).one()
recipe_ids_list.append(recipe_id_append.recipe_id)
return recipe_ids_list
def get_ingredients_by_recipe_id(recipe_id):
"""Return ingredients for given recipe_id.
>>> get_ingredients_by_recipe_id('08Ifren64xtMVpoG03Qx')
[
<Ingredient ingredient_id=1,
recipe_id=08Ifren64xtMVpoG03Qx,
detailed_ingredient=1 can TJ's Buttermil>
,
<Ingredient ingredient_id=2,
recipe_id=08Ifren64xtMVpoG03Qx,
detailed_ingredient=1 package TJ's Soy C>
,
<Ingredient ingredient_id=3,
recipe_id=08Ifren64xtMVpoG03Qx,
detailed_ingredient=2/3 cup TJ's Island >
,
<Ingredient ingredient_id=4,
recipe_id=08Ifren64xtMVpoG03Qx,
detailed_ingredient=1 cup TJ's Unsweeten>
,
<Ingredient ingredient_id=5,
recipe_id=08Ifren64xtMVpoG03Qx,
detailed_ingredient=TJ's Fire Roasted Di>
]
"""
return db.session.query(Ingredient).filter_by(recipe_id=recipe_id).all()
def get_abridged_ingredients_by_title(title):
"""Return multiple tags.
"""
ingredients_list = []
ingredients = db.session.query(Ingredient).join(Recipe).filter(Recipe.title == title).all()
for ingredient in ingredients:
ingredients_list.append(ingredient.abridged_ingredient)
return ingredients_list
def resources_page():
"""
Populates my resources.js page through a resourcespage.txt.
# Test that each line has 4 fields
count = 0
for character in line:
if character == '|':
count += 1
if count !== 3:
print("check line:", index + 1, "has", count + 1, "fields instead of 4.")
"""
resources_file = open("resourcespage.txt")
resources_list = []
for index, line in enumerate(resources_file):
line_data=line.rstrip().split("|")
topic = line_data[0]
details = line_data[1]
uses = line_data[2]
resource_url = line_data[3]
current_dict = {}
current_dict['number'] = index
current_dict['topic'] = topic
current_dict['details'] = details
current_dict['uses'] = uses
current_dict['resource_url'] = resource_url
resources_list.append(current_dict)
print(resources_list)
return (resources_list)
def get_ingredients():
"""Return all ingredients."""
return Ingredient.query.all()
# This connects to the database when running crud.py interactively
if __name__ == '__main__':
from server import app
connect_to_db(app)