Creating a recipe app that allows users to search for recipes based on ingredients they have is a great idea for simplifying meal planning and reducing food waste. To implement this, we’ll use Python along with some popular libraries like Flask for building the web application and SQLite for storing recipe data.
First, let’s set up the project structure. We’ll create a directory for our project and inside that, we’ll have separate files for our Python code and templates for the HTML pages. Here’s how the structure might look:
recipe_app/
│
├── app.py
├── templates/
│ ├── index.html
│ ├── recipe.html
│ └── error.html
└── database.db
Now, let’s start with the Python code. We’ll use Flask to create a web application. Flask allows us to create routes for different URLs and render HTML templates.
# app.py
from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
# Connect to the SQLite database
conn = sqlite3.connect('database.db')
c = conn.cursor()
# Define the route for the home page
@app.route('/')
def index():
return render_template('index.html')
# Define the route for searching recipes
@app.route('/search', methods=['POST'])
def search():
ingredients = request.form['ingredients'].split(',')
query = "SELECT * FROM recipes WHERE "
placeholders = []
for ingredient in ingredients:
placeholders.append("ingredients LIKE ?")
query += " AND ".join(placeholders)
c.execute(query, ['%'+ingredient.strip()+'%' for ingredient in ingredients])
recipes = c.fetchall()
if not recipes:
return render_template('error.html', message="No recipes found!")
return render_template('recipe.html', recipes=recipes)
if __name__ == '__main__':
app.run(debug=True)
In this code, we first import Flask and SQLite libraries. We create an instance of the Flask class and connect to the SQLite database. Then, we define routes for the home page and the search functionality. When a user submits a list of ingredients, we query the database to find recipes that include those ingredients. If no recipes are found, we render an error message.
Now, let’s create the HTML templates for the user interface. We’ll have one template for the home page where users can enter ingredients and another template to display search results.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recipe App</title>
</head>
<body>
<h1>Recipe Search</h1>
<form action="/search" method="post">
<label for="ingredients">Enter ingredients (separated by commas):</label><br>
<input type="text" id="ingredients" name="ingredients"><br>
<button type="submit">Search</button>
</form>
</body>
</html>
<!-- recipe.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recipe Results</title>
</head>
<body>
<h1>Recipes</h1>
<ul>
{% for recipe in recipes %}
<li>{{ recipe[1] }} - {{ recipe[2] }}</li>
{% endfor %}
</ul>
</body>
</html>
<!-- error.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<h1>Error</h1>
<p>{{ message }}</p>
</body>
</html>
These HTML templates define the structure of our web pages. The index.html template includes a form where users can enter ingredients, and the recipe.html template displays the search results. If no recipes are found, the error.html template is rendered with an appropriate message.
Next, let’s create the SQLite database and populate it with some sample recipe data. We’ll create a table called “recipes” with columns for recipe name, ingredients, cooking time, and nutritional information.
# Create the SQLite database and table
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
# Create recipes table
c.execute('''CREATE TABLE recipes
(id INTEGER PRIMARY KEY,
name TEXT,
ingredients TEXT,
cooking_time INTEGER,
nutrition TEXT)''')
# Insert sample data
recipes = [
('Spaghetti Carbonara', 'spaghetti, bacon, eggs, Parmesan cheese', 20, 'Calories: 450, Fat: 20g, Carbs: 30g, Protein: 25g'),
('Chicken Stir-Fry', 'chicken breast, broccoli, carrots, soy sauce', 30, 'Calories: 300, Fat: 10g, Carbs: 20g, Protein: 35g'),
('Vegetable Curry', 'potatoes, cauliflower, peas, curry paste', 40, 'Calories: 250, Fat: 8g, Carbs: 35g, Protein: 10g')
]
c.executemany('INSERT INTO recipes (name, ingredients, cooking_time, nutrition) VALUES (?, ?, ?, ?)', recipes)
conn.commit()
conn.close()
This code creates the recipes table in the SQLite database and inserts some sample recipe data. Each recipe is represented as a tuple with the name, ingredients, cooking time, and nutritional information.
Now that we have everything set up, we can run our Flask app by executing the app.py file. This will start a web server locally, and we can access our recipe app by navigating to http://localhost:5000/ in a web browser.
Users can enter ingredients they have in the search form, and the app will display recipes that include those ingredients along with their cooking times and nutritional information. If no recipes are found, an error message is displayed.
Overall, this recipe app provides a simple and user-friendly way for people to search for recipes based on the ingredients they have on hand. It’s a great tool for meal planning and reducing food waste by making the most out of available ingredients.
How to test this code and what responses you might expect.
- Accessing the App: After running the Flask server (
app.py
), open a web browser and navigate tohttp://localhost:5000/
. You should see the home page of the recipe app, prompting you to enter ingredients. - Searching for Recipes: Enter a list of ingredients separated by commas in the input field and click “Search”. The app will display recipes that include those ingredients, along with their cooking times and nutritional information.
- Viewing Recipe Results: Upon successful search, you’ll see a list of recipes matching your ingredients on the screen. Each recipe will be displayed with its name and cooking time.
- Error Handling: If you enter ingredients that don’t match any recipes in the database, an error message will be displayed informing you that no recipes were found.
- Database Initialization: Before testing the app, ensure that the SQLite database (
database.db
) is created and populated with sample recipe data. This initialization script should be executed separately from the Flask app.
By following these steps, you can effectively test the recipe app and observe its responses. If you encounter any issues or need further assistance, feel free to ask!