Improved delete, scaling added

This commit is contained in:
lucas
2022-04-29 17:11:38 -07:00
parent 479d38464e
commit 0ab4c37785
7 changed files with 202 additions and 134 deletions

35
main.py
View File

@@ -4,9 +4,7 @@ Written by Lucas Jensen
Last updated 3/29/22 for Assignment 1 Last updated 3/29/22 for Assignment 1
""" """
from flask import Flask, redirect, render_template, request from flask import Flask, redirect, render_template, request
from markupsafe import escape from recipe import Recipe, RecipeBook
from recipe import Recipe, RecipeBook, open_json
app = Flask(__name__) app = Flask(__name__)
@@ -17,39 +15,42 @@ def home():
@app.route('/recipes', methods=['GET']) @app.route('/recipes', methods=['GET'])
def ReturnJSON(): def recipes_page():
recipes = open_json() recipes = book.get_recipes()
# recipes is a dictionary of recipe objects
if recipes == {}: if recipes == {}:
return render_template("empty.html") return render_template("empty.html")
return render_template("recipes.html", content=recipes) return render_template("recipes.html", content=recipes)
@app.route('/recipes/<_id>', methods=['GET']) @app.route('/recipes/<_id>', methods=['GET', 'POST'])
def recipe_page(_id): def recipe_page(_id):
if request.method == 'GET':
recipe = book.find_by_id(_id) recipe = book.find_by_id(_id)
if request.method == 'POST':
scale = request.form.get('scale')
new = recipe.scale(scale)
new_id = book.add_recipe(new)
return redirect(f'/recipes/{new_id}')
return render_template("recipe.html", content=recipe, _id=_id) return render_template("recipe.html", content=recipe, _id=_id)
@app.route('/recipes/<_id>/delete') @app.route('/recipes/<_id>/delete')
def delete_recipe(_id): def delete_recipe(_id):
book.delete(_id) book.find_and_delete(_id)
return redirect("/recipes") return redirect("/recipes")
@app.route('/add', methods=['GET', 'POST']) @app.route('/add', methods=['GET', 'POST'])
def add_recipe(): def add_recipe():
if request.method == "POST": if request.method == "POST":
flour = request.form.get("flour_weight") new_recipe = Recipe(request.form.get('name'), request.form.get('yield'))
water = request.form.get("water_weight") for item in request.form:
salt = request.form.get("salt_weight") if item not in ['name', 'yield']:
loaves = request.form.get("yield") new_recipe.add_ingredient(item, int(request.form.get(item)))
name = request.form.get("name")
new_recipe = Recipe(name, loaves, flour, water, salt) book.add_recipe(new_recipe)
book.add_recipes(new_recipe)
return redirect("/recipes") return redirect("/recipes")
return render_template("new.html") return render_template("new.html")
@@ -57,4 +58,4 @@ def add_recipe():
if __name__ == "__main__": if __name__ == "__main__":
book = RecipeBook() book = RecipeBook()
app.run(debug=True) app.run(debug=False)

201
recipe.py
View File

@@ -3,7 +3,11 @@ Written by Lucas Jensen
Portfolio Project for CS361 Portfolio Project for CS361
The main logic behind a recipe The main logic behind a recipe
""" """
import json import json
from pprint import pprint
JSON_FILE = "recipes/recipes.json"
class RecipeBook: class RecipeBook:
@@ -11,38 +15,29 @@ class RecipeBook:
Represents a recipe book containing several bread recipes Represents a recipe book containing several bread recipes
""" """
def __init__(self): def __init__(self):
self._recipes = self.__build_recipes() self._recipes = {} # a dictionary of recipe objects, ID as key
self._id = 0
self.__build_recipes()
@staticmethod def __build_recipes(self):
def __build_recipes():
""" """
Builds the recipe book from an existing json file Builds the recipe book from an existing json file
:return:
""" """
with open("recipes/recipes.json", "rt") as f: with open(JSON_FILE, 'rt') as f:
recipes = json.load(f) recipes_dict = json.load(f)
return recipes for _id in recipes_dict:
recipe_dict = recipes_dict[_id]
recipe = Recipe(recipe_dict['name'], recipe_dict['quantity'])
recipe.set_id(_id)
ingredients = recipe_dict['ingredients']
for ingredient in ingredients:
recipe.add_ingredient(ingredient, ingredients[ingredient])
recipe.add_ingredient(ingredient, ingredients[ingredient])
self._recipes[_id] = recipe
def add_recipes(self, recipe: object) -> None: def get_recipes(self):
"""
Adds a recipe to the book
:param recipe: bread recipe object
:return: nothing
"""
keys = open_json()
count = 0
while str(count) in keys:
count += 1
self._recipes[count] = recipe
self.save(count, recipe)
def get_recipes(self) -> list:
"""
get the dict of recipes
:return: the dict of recipes
"""
return self._recipes return self._recipes
def find_by_id(self, _id: int) -> object: def find_by_id(self, _id: int) -> object:
@@ -51,58 +46,83 @@ class RecipeBook:
:param _id: int, the id of the recipe :param _id: int, the id of the recipe
:return: recipe object :return: recipe object
""" """
return self._recipes[_id] return self._recipes[str(_id)]
def save(self, _id: int, recipe: object) -> None: def find_and_delete(self, _id):
""" """
Saves a recipe to the JSON file Finds a recipe using its ID and deletes it
:param _id: int :param _id: int of the recipe's ID
:return: nothing
"""
self._recipes[_id] = recipe.get_recipe()
with open("recipes/recipes.json", "wt") as f:
json.dump(self._recipes, f, indent=4)
def delete(self, _id: int) -> None:
"""
Deletes a recipes as found by its ID
:param _id: int: id of the recipe
:return: nothing :return: nothing
""" """
del self._recipes[str(_id)] del self._recipes[str(_id)]
with open("recipes/recipes.json", "wt") as f: # remove from JSON file
json.dump(self._recipes, f, indent=4) with open(JSON_FILE, 'rt') as f:
json_file = json.load(f)
pprint(json_file)
del json_file[str(_id)]
with open(JSON_FILE, 'wt') as f:
json.dump(json_file, f, indent=4)
def add_recipe(self, recipe):
"""
appends a recipe object to the recipe book
:param recipe: recipe object
:return: the id of the newly stored recipe
"""
with open(JSON_FILE, 'rt') as f:
keys = json.load(f)
while str(self._id) in keys:
self._id += 1
recipe.set_id(self._id)
saved_id = self._id
self._recipes[str(self._id)] = recipe
self._id += 1
# pprint(self._recipes)
self.save(recipe)
return saved_id
@staticmethod
def save(recipe):
"""
appends a recipe dictionary to the JSON file
:param recipe:
:return:
"""
with open(JSON_FILE, 'rt') as f:
recipe_dict = json.load(f)
recipe_dict[recipe.get_id()] = recipe.get_recipe()
with open(JSON_FILE, 'wt') as f:
json.dump(recipe_dict, f, indent=4)
class Recipe: class Recipe:
""" """
Represents a bread recipe Represents a bread recipe
""" """
def __init__(self, name, num_loaves, ap_flour, water, salt): def __init__(self, name: str, num_loaves: int):
self._name = name self._name = name
self._num_loaves = num_loaves self._num_loaves = num_loaves
self._ingredients = { self._ingredients = {}
'ap_flour': ap_flour, self._id = None
'water': water,
'salt': salt
}
def get_name(self) -> str:
"""
Gets the name of a recipe
:return:
"""
return self._name
def get_recipe(self) -> dict: def get_recipe(self) -> dict:
""" """
:return: returns the whole recipe as a dict, including quantity builds and returns the whole recipe as a single dictionary
:return: dictionary
""" """
recipe_dict = { recipe_dict = {
'quantity': self._num_loaves, 'quantity': self._num_loaves,
'name': self._name, 'name': self._name,
# 'id': self._id,
'ingredients': {} 'ingredients': {}
} }
@@ -111,18 +131,21 @@ class Recipe:
return recipe_dict return recipe_dict
def get_name(self) -> str:
return self._name
def get_num_loaves(self) -> int: def get_num_loaves(self) -> int:
"""
:return: int: number of loaves the recipe calls for
"""
return self._num_loaves return self._num_loaves
def get_ingredients(self) -> dict: def get_ingredients(self) -> dict:
"""
:return: dictionary of all ingredients
"""
return self._ingredients return self._ingredients
def get_id(self) -> int:
return self._id
def set_id(self, _id):
self._id = _id
def add_ingredient(self, name: str, mass: int) -> None: def add_ingredient(self, name: str, mass: int) -> None:
""" """
Adds an ingredient to the recipe. Mass in grams. Adds an ingredient to the recipe. Mass in grams.
@@ -132,54 +155,50 @@ class Recipe:
""" """
self._ingredients[name] = mass self._ingredients[name] = mass
def scale(self, new_num: int) -> object: def scale(self, new_num) -> object:
""" """
Scales the recipe by a given factor Scales the recipe by a given factor
:param new_num: integer, the number of desired loaves :param new_num: integer, the number of desired loaves
:return: Recipe object, now scaled :return: Recipe object, now scaled
""" """
scale = new_num / self._num_loaves scale = int(new_num) / int(self._num_loaves)
ap_flour = self._ingredients['ap_flour'] * scale scaled_recipe = Recipe(f"{self._name} * {scale}", new_num)
water = self._ingredients['water'] * scale
salt = self._ingredients['salt'] * scale
name = f"{self._name} * {scale}"
scaled_recipe = Recipe(name, new_num, ap_flour, water, salt)
for ingredient in self._ingredients: for ingredient in self._ingredients:
if ingredient not in ['ap_flour', 'water', 'salt']:
mass = self._ingredients[ingredient] * scale mass = self._ingredients[ingredient] * scale
scaled_recipe.add_ingredient(ingredient, mass) scaled_recipe.add_ingredient(ingredient, round(mass))
return scaled_recipe return scaled_recipe
def default_recipes(): def default_recipes():
recipe_1 = Recipe('Country Brown', 1, 600, 300, 13) """Adds some sample data"""
recipe_2 = Recipe('Conventional White', 2, 1000, 700, 25) recipe_1 = Recipe('Country Brown', 1)
recipe_2 = Recipe('Conventional White', 2)
sample_recipes = [recipe_1, recipe_2]
flour = 500
water = 300
salt = 12
for recipe in sample_recipes:
recipe.add_ingredient("AP Flour", flour)
flour += 500
recipe.add_ingredient("Water", water)
water += 300
recipe.add_ingredient("salt", salt)
salt += 12
recipe_3 = recipe_2.scale(4) recipe_3 = recipe_2.scale(4)
return [recipe_1, recipe_2, recipe_3] sample_recipes.append(recipe_3)
return sample_recipes
def open_json():
"""TODO"""
with open('recipes/recipes.json') as f:
data = json.load(f)
return data
if __name__ == "__main__": if __name__ == "__main__":
recipes = default_recipes() recipes = default_recipes()
book = RecipeBook() book = RecipeBook()
for recipe in recipes: for recipe in recipes:
book.add_recipes(recipe) book.add_recipe(recipe)
# for recipe in book.get_recipes():
# print(book.get_recipes()[recipe])
#
# rec = Recipe('sandwich loaf', 2, 1000, 700, 25)
# rec.add_ingredient('ww flour', 500)
# rec.save('recipes.json')

View File

@@ -1,11 +1,26 @@
{ {
"0": { "3": {
"quantity": "2", "quantity": "2",
"name": "Sourdough", "name": "Sourdough",
"ingredients": { "ingredients": {
"ap_flour": "1000", "AP Flour": 800,
"water": "600", "WW Flour": 200,
"salt": "20" "Water": 700,
"Salt": 20,
"Yeast": 0,
"Starter": 50
}
},
"7": {
"quantity": "5",
"name": "Sourdough * 2.5",
"ingredients": {
"AP Flour": 2000,
"WW Flour": 500,
"Water": 1750,
"Salt": 50,
"Yeast": 0,
"Starter": 125
} }
} }
} }

View File

@@ -1,6 +1,7 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" /> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@@ -26,4 +27,7 @@
&copy; Copyright 2022 by <a href="https://github.com/ljensen505">Lucas Jensen</a>. &copy; Copyright 2022 by <a href="https://github.com/ljensen505">Lucas Jensen</a>.
{% endblock %} {% endblock %}
</div> </div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body> </body>

View File

@@ -7,23 +7,44 @@
{% block content %} {% block content %}
<h1>New Recipe</h1> <h1>New Recipe</h1>
<form action="{{ url_for("add_recipe")}}" method="post"> <form action="{{ url_for("add_recipe")}}" method="post">
<label for="name">Recipe Name:</label><br> <table>
<input required type="text" id="name" name="name" placeholder="Sourdough"> <tr>
<br> <td>
<p>Enter all values grams.</p> <label for="name">Recipe Name:</label>
</td>
<td>
<input required type="text" id="name" name="name" placeholder="Sourdough">
</td>
</tr>
<td>
<label for="yield">Loaves:</label>
</td>
<td>
<input required type="number" id="yield" name="yield" placeholder="2">
</td>
</table>
{% for ing in ['flour', 'water', 'salt'] %} <p>Enter all values grams. If an ingredient is not needed, input 0.</p>
<label for="{{ing}}_weight">{{ing.title()}}:</label><br>
<input required type="number" id="{{ing}}_weight" name="{{ing}}_weight" placeholder="100"><br>
<br>
{% endfor %}
<label for="yield">Loaves:</label><br> <table>
<input required type="number" id="yield" name="yield" placeholder="2"> <tr>
<th>Ingredient</th>
<th>Mass in g</th>
</tr>
{% for item in ['AP Flour', 'WW Flour', 'Rye Flour', 'Water', 'Salt', 'Yeast', 'Starter'] %}
<tr>
<td><label for="{{item}}_weight">{{item}}:</label></td>
<td><input required type="number" id="{{item}}_weight" name="{{item}}" placeholder="500"></td>
</tr>
{% endfor %}
</table>
<button type="submit">Add!</button> <button type="submit">Add!</button>

View File

@@ -1,5 +1,5 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}{{content["name"]}}{% endblock %} {% block title %}{{content.get_name()}}{% endblock %}
{% block html_head %} {% block html_head %}
@@ -7,24 +7,31 @@
{% block content %} {% block content %}
<h1>{{content["name"]}} Recipe</h1> <h1>{{ content.get_name() }} Recipe</h1>
<p>Number of loaves: {{content['quantity']}}</p> <p>Number of loaves: {{ content.get_num_loaves() }}</p>
<table> <table>
<tr> <tr>
<th>Ingredient</th> <th>Ingredient</th>
<th>Grams</th> <th>Grams</th>
</tr> </tr>
{% for item in content['ingredients'] %} {% for item in content.get_ingredients() %}
<tr> <tr>
<td>{{ item.title() }}</td> <td>{{ item }}</td>
<td>{{ content['ingredients'][item] }}</td> <td>{{ content.get_ingredients()[item] }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
<h2>Scaling</h2>
<form method="post">
<label for="scale_btn">How many loaves do you want: </label>
<input required name="scale" id="scale_btn" type="number">
<button type="submit">Go!</button>
</form>
<input type="button" onclick="location.href='/recipes/{{_id}}/delete'" value=Delete /> <input type="button" onclick="location.href='/recipes/{{_id}}/delete'" value=Delete />

View File

@@ -11,7 +11,8 @@
<ul> <ul>
{% for recipe in content %} {% for recipe in content %}
<li> <li>
<a href=recipes/{{recipe}}>{{content[recipe]['name']}}</a> <a href=recipes/{{recipe}}>{{content[recipe].get_name()}}</a>
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>