Flask is a lightweight and flexible web framework for Python that enables developers to build web applications quickly and efficiently. It is known for its simplicity and minimalism, making it a great choice for beginners and small to medium-sized projects.
Lesson Outline:
- Setting Up a Flask Project
- Creating Routes and Views
- Handling Forms and Templates
1. Setting Up a Flask Project
Installing Flask:
- Use pip to install Flask:
pip install Flask - Verify the installation:
python -m flask –version
Creating a Basic Project Structure:
- py: Main application file
- templates/: Directory for HTML templates
- static/: Directory for CSS, JavaScript, images
Basic Flask App Example:
app = Flask(__name__)
@app.route(‘/’)
def home():
return “Hello, Flask!”
if __name__ == ‘__main__’:
app.run(debug=True)
- Run the app:
python app.py - Visit http://127.0.0.1:5000/to see the output.
2. Creating Routes and Views
Understanding Routes:
- Routes define the URL patterns for your web application.
- The @app.route()decorator binds a URL to a function (view).
Example:
def about():
return “This is the About page.”
- Access this view via http://127.0.0.1:5000/about
Dynamic Routes:
def show_user(username):
return f”Hello, {username}!”
- This handles dynamic URLs like /user/John
3. Handling Forms and Templates
Using HTML Templates:
- Create a templates
Add an index.html file:
<html>
<head><title>Flask App</title></head>
<body>
<h1>Welcome to Flask!</h1>
</body>
- </html>
Rendering Templates in Flask:
@app.route(‘/’)
def home():
return render_template(‘index.html’)
Handling Forms:
<form method=”POST” action=”/submit”>
<input type=”text” name=”username” placeholder=”Enter your name”>
<input type=”submit” value=”Submit”>
- </form>
Processing Form Data:
@app.route(‘/submit’, methods=[‘POST’])
def submit():
username = request.form[‘username’]
return f”Hello, {username}!”
Conclusion:
- Flask provides a simple yet powerful framework to build web applications.
- You’ve learned how to set up a project, create routes, and handle forms with templates.
Next, we’ll dive deeper into advanced Flask features like blueprints, REST APIs, and database integration.
Leave a Reply