Step 1: Set Up Your Environment
- Install Flask: You can set up a virtual environment and install Flask.
python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` pip install Flask
- Project Structure:
recipe_community/ ├── app.py ├── templates/ │ ├── index.html │ ├── add_recipe.html └── static/ └── style.css
Step 2: Create the Backend (app.py)
Here’s a simple Flask application to handle recipe submissions:
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# In-memory storage for recipes (you can replace this with a database later)
recipes = []
@app.route('/')
def index():
return render_template('index.html', recipes=recipes)
@app.route('/add', methods=['GET', 'POST'])
def add_recipe():
if request.method == 'POST':
title = request.form['title']
ingredients = request.form['ingredients']
instructions = request.form['instructions']
recipes.append({
'title': title,
'ingredients': ingredients.split(','),
'instructions': instructions
})
return redirect(url_for('index'))
return render_template('add_recipe.html')
if __name__ == '__main__':
app.run(debug=True)
Step 3: Create the Frontend (HTML Templates)
- index.html (to display recipes):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <title>Recipe Sharing Community</title> </head> <body> <h1>Recipe Sharing Community</h1> <a href="/add">Add a Recipe</a> <ul> {% for recipe in recipes %} <li> <h2>{{ recipe.title }}</h2> <h3>Ingredients:</h3> <ul> {% for ingredient in recipe.ingredients %} <li>{{ ingredient }}</li> {% endfor %} </ul> <h3>Instructions:</h3> <p>{{ recipe.instructions }}</p> </li> {% endfor %} </ul> </body> </html>
- add_recipe.html (to add new recipes):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <title>Add Recipe</title> </head> <body> <h1>Add a New Recipe</h1> <form method="POST"> <label for="title">Recipe Title:</label><br> <input type="text" id="title" name="title" required><br> <label for="ingredients">Ingredients (comma-separated):</label><br> <input type="text" id="ingredients" name="ingredients" required><br> <label for="instructions">Instructions:</label><br> <textarea id="instructions" name="instructions" required></textarea><br> <button type="submit">Submit Recipe</button> </form> <a href="/">Back to Home</a> </body> </html>
Step 4: Add Some Basic CSS (style.css)
You can create a simple CSS file to style your application:
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1, h2, h3 {
color: #333;
}
ul {
list-style-type: none;
padding: 0;
}
form {
margin-bottom: 20px;
}
Step 5: Run Your Application
Now you can run your Flask app:
python app.py
Leave a Reply