MeowalsoMeow

foodbackend_stage5

Sep 12th, 2021
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.72 KB | None | 0 0
  1. import sqlite3
  2. import sys
  3. import argparse
  4.  
  5.  
  6. class FoodBlog:
  7. def __init__(self):
  8. # self.database()
  9. args = sys.argv
  10. self.db_name = args[1]
  11. self.conn = sqlite3.connect(self.db_name)
  12. self.cursor = self.conn.cursor()
  13. self.data = {"meals": ("breakfast", "brunch", "lunch", "supper"),
  14. "ingredients": ("milk", "cacao", "strawberry", "blueberry", "blackberry", "sugar"),
  15. "measures": ("ml", "g", "l", "cup", "tbsp", "tsp", "dsp", "")}
  16. self.meal_ids_names = ()
  17. self.recipe_name = ''
  18. self.all_meals_names = []
  19. self.ingredients_names = []
  20.  
  21. def make_table(self, table=None, name=None, description=None):
  22. # This function creates tables. It inserts data when name is given
  23. item = f'{table[:-1]}'
  24. not_null = 'NOT NULL' if table in ['ingredients', 'meals', 'recipes'] else '' # control null or not
  25. if table == 'recipes':
  26. des = f',{item}_description TEXT'
  27. else:
  28. des = ''
  29. # with sqlite3.connect(db_name) as data:
  30. # cursor = data.cursor()
  31. uni = 'UNIQUE' if table != 'recipes' else ''
  32. if name is None:
  33. self.cursor.execute(f'''
  34. CREATE TABLE IF NOT EXISTS {table}(
  35. {item}_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  36. {item}_name TEXT {not_null} {uni}
  37. {des}
  38. );
  39. ''')
  40. else:
  41. if table == 'recipes':
  42. self.cursor.execute(f'''
  43. INSERT into {table} ({table[:-1]}_description, {table[:-1]}_name) VALUES (?, ?);
  44. ''', (description, name))
  45. else:
  46. self.cursor.execute(f'''
  47. INSERT into {table} ({table[:-1]}_name) VALUES (?);
  48. ''', (name,))
  49. self.cursor.execute('''
  50. SELECT * FROM meals
  51. ''')
  52. self.meal_ids_names = self.cursor.fetchall()
  53. self.conn.commit()
  54.  
  55. def make_serve_table(self):
  56. self.cursor.execute('PRAGMA foreign_keys = ON;')
  57. self.cursor.execute(f'''
  58. CREATE TABLE IF NOT EXISTS serve(
  59. serve_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  60. meal_id INTEGER NOT NULL,
  61. recipe_id INTEGER NOT NULL,
  62. FOREIGN KEY (meal_id)
  63. REFERENCES meals (meal_id),
  64.  
  65. FOREIGN KEY (recipe_id)
  66. REFERENCES recipes (recipe_id)
  67. );
  68. ''')
  69. self.conn.commit()
  70.  
  71. def make_quantity_table(self):
  72. self.cursor.execute('''
  73. CREATE TABLE IF NOT EXISTS quantity(
  74. quantity_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  75. quantity INTEGER NOT NULL,
  76. recipe_id INTEGER NOT NULL,
  77. measure_id INTEGER NOT NULL,
  78. ingredient_id INTEGER NOT NULL,
  79. FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id),
  80. FOREIGN KEY(measure_id) REFERENCES measures(measure_id),
  81. FOREIGN KEY (ingredient_id) REFERENCES ingredients(ingredient_id)
  82. );
  83. ''')
  84. self.conn.commit()
  85.  
  86. def get_id(self, table_name, name):
  87. # This function checks if the user input will get more than one result in ingredients and measures
  88. # it then returns id
  89. # e.g : t for tbs and tbsp. berry for blueberry and strawberry. t and berry won't pass
  90. self.cursor.execute(f'''
  91. SELECT {table_name}_id FROM {table_name}s WHERE {table_name}_name LIKE (?)
  92. ''', ('%' + name + '%',))
  93. fetched = self.cursor.fetchone()
  94. fetched_all = self.cursor.fetchall()
  95. #print('fetched', fetched)
  96. #print('fetched all', fetched_all)
  97. if fetched and len(fetched_all) <= 1 or name == '':
  98. return int(fetched[0])
  99. else:
  100. print(table_name, name)
  101. print("This data doesn't exist")
  102. return False
  103.  
  104. def change_serve_table(self, name):
  105. # insert into table serve with recipe_id meal_id
  106. self.cursor.execute('''
  107. SELECT recipe_id FROM recipes WHERE recipe_name = (?)
  108. ''', (name,)) # fetch all recipe names are not unique there are duplicates
  109. recipe_id = self.cursor.fetchone()
  110.  
  111. all_meals_names = [x[1] for x in self.meal_ids_names]
  112. all_meals_ids = [x[0] for x in self.meal_ids_names]
  113. # print(all_meals_ids, all_meals_names)
  114. # [1, 2, 3, 4]['breakfast', 'brunch', 'lunch', 'supper']
  115.  
  116. for x in range(len(all_meals_names)):
  117. print(f'{x + 1}) {all_meals_names[x]}', end=' ')
  118. print()
  119. print('When the dish can be served: ', end='')
  120. wanted_meals = input().split()
  121. for i in wanted_meals:
  122. self.cursor.execute('''
  123. INSERT INTO serve( meal_id, recipe_id) VALUES (?, ?);
  124. ''', (int(i), recipe_id[0]))
  125. self.conn.commit()
  126.  
  127. def change_quantity_table(self):
  128. # insert into quantity table with recipe_id, measure_id, ingredient_id
  129. while True:
  130. print('Input quantity of ingredient <press enter to stop>:')
  131. quans = []
  132. quan_ids = []
  133. q = input().split()
  134. if len(q) == 2:
  135. print('insert q', q)
  136. q.insert(1, '')
  137. print('inserted', q)
  138.  
  139. if q:
  140. quans.extend(q)
  141. if self.get_id('measure', quans[1]) and self.get_id('ingredient', quans[2]):
  142. quan_ids.extend(
  143. [int(quans[0]), self.get_id('recipe', self.recipe_name), self.get_id('measure', quans[1]),
  144. self.get_id('ingredient', quans[2])])
  145. print('add to db')
  146. self.cursor.execute('''
  147. INSERT INTO quantity (quantity, recipe_id, measure_id, ingredient_id) VALUES (?, ?, ?, ?)
  148. ''', (quan_ids[0], quan_ids[1], quan_ids[2], quan_ids[3]))
  149. self.conn.commit()
  150. else:
  151. print('else q', q, len(q))
  152. continue # if len(q) == 2
  153. else:
  154. print('end of loop q', quans)
  155. break
  156.  
  157. def database(self):
  158. for x in self.data:
  159. self.make_table(x)
  160. print('execute time', x)
  161. for y in self.data[x]:
  162. self.make_table(x, y)
  163. self.make_table('recipes')
  164.  
  165. def do_args(self):
  166. self.cursor.execute('''
  167. SELECT * FROM ingredients
  168. ''')
  169. self.ingredients_names = self.cursor.fetchall()
  170. print(self.ingredients_names)
  171. parser = argparse.ArgumentParser()
  172. parser.add_argument('--ingredients', choices=self.ingredients_names)
  173. parser.add_argument('--meals', choices=self.all_meals_names)
  174. parser.add_argument('food_blog.db')
  175. args = parser.parse_args()
  176. wanted_ingredients = args.ingredients
  177. if wanted_ingredients:
  178. wanted_ingri_ids = []
  179. for i in wanted_ingredients:
  180. self.cursor.execute('''
  181. SELECT ingredient_id FROM ingredients WHERE ingredient_name = (?)
  182. ''', (i,))
  183. wanted_ingri_ids.append(self.cursor.fetchone())
  184. wanted_meals = args.meals
  185. for _id in wanted_ingri_ids:
  186. self.cursor.execute('''
  187. SELECT recipe_name FROM recipes AS r
  188. INNER JOIN quantity AS q ON r.recipe_id = q.recipe_id
  189. INNER JOIN ingredients AS i ON i.ingredient_id = (?)
  190. INNER JOIN serve AS s ON s.recipe_id = r.recipe_id
  191. INNER JOIN meals AS m ON s.meal_id = m.meal_id
  192. WHERE m.meal_name IN (?)
  193. ''', (_id, wanted_meals))
  194. recipes = self.cursor.fetchall()
  195. if recipes:
  196. print('Recipes selected for you: ', *recipes)
  197. else:
  198. print('There are no such recipes in the database.')
  199.  
  200. def menu(self):
  201. self.database()
  202. self.make_serve_table()
  203. self.make_quantity_table()
  204. #self.do_args()
  205. # move the make db bases lines above in function database() after the tests are passed
  206. print('Pass the empty recipe name to exit.')
  207. while True:
  208. self.recipe_name = input('Recipe name: ')
  209. if self.recipe_name == '':
  210. break
  211. des = input('Recipe description: ')
  212. self.make_table(table='recipes', name=self.recipe_name, description=des)
  213. self.change_serve_table(self.recipe_name)
  214. self.change_quantity_table() # this function deals with input
  215. self.conn.close()
  216.  
  217.  
  218. FoodBlog().menu()
  219.  
Advertisement
Add Comment
Please, Sign In to add comment