Web Development with Flask
Welcome to Web Development with Flask! Think of Flask as a Swiss Army knife for building websites - itβs lightweight, flexible, and perfect for learning web development fundamentals.
What Youβll Learn
This module covers modern web development with Flask:
- Flask Basics - Setting up your first web application
- Routes & Views - Handling URLs and HTTP requests
- Templates - Creating dynamic HTML with Jinja2
- Forms - Processing user input and validation
- Databases - Storing and retrieving data with SQLAlchemy
- Authentication - User login and session management
Why Flask Matters
Flask is the perfect starting point for web development because:
- Simple to Learn - Minimal concepts to understand
- Python-Powered - Use all your Python skills
- Flexible - Build anything from simple sites to complex apps
- Production Ready - Used by companies like Netflix and Airbnb
- Large Ecosystem - Thousands of extensions available
Real-World Applications
Flask powers:
- Web APIs - Backend services for mobile apps
- Content Management Systems - Blogs, news sites, e-commerce
- Data Dashboards - Analytics and reporting tools
- REST APIs - Microservices and API-first applications
- Admin Panels - Internal tools and management interfaces
Module Structure
10-web-development/
βββ 01-flask-basics.md # Your first Flask app
βββ 02-routes-views.md # URL routing and view functions
βββ 03-templates.md # Jinja2 templating
βββ 04-forms.md # Form handling and validation
βββ 05-databases.md # SQLAlchemy and data persistence
βββ 06-authentication.md # User authentication and sessions
Prerequisites
Before starting this module, you should be comfortable with:
- Python basics (functions, classes, imports)
- Basic HTML (tags, forms, links)
- HTTP concepts (GET, POST, URLs)
- Command line usage
Learning Approach
Each lesson includes:
- Complete Code Examples - Working Flask applications
- Step-by-Step Setup - Get running quickly
- Real-World Patterns - Professional development practices
- Debugging Tips - Common issues and solutions
- Exercises - Build your own features
Flask Architecture
Request-Response Cycle
# Browser β Flask App β Response
# 1. User types URL or clicks link
# 2. Browser sends HTTP request to Flask
# 3. Flask matches URL to route function
# 4. Route function processes request
# 5. Flask returns HTTP response
# 6. Browser displays response
MVC Pattern in Flask
Model (Data) β SQLAlchemy models
View (Display) β Jinja2 templates
Controller (Logic) β Flask routes
Key Flask Concepts
Routes and View Functions
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to my website!"
@app.route('/about')
def about():
return "Learn more about us"
Templates with Jinja2
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<nav>{% block nav %}{% endblock %}</nav>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
Forms and Validation
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class ContactForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
submit = SubmitField('Send')
Database Models
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __repr__(self):
return f'<User {self.username}>'
Development Environment
Project Structure
flask_app/
βββ app/
β βββ __init__.py
β βββ routes.py
β βββ models.py
β βββ forms.py
β βββ templates/
β βββ base.html
β βββ index.html
βββ config.py
βββ run.py
βββ requirements.txt
βββ .env
Virtual Environment
# Create virtual environment
python -m venv venv
# Activate (Windows)
venv\Scripts\activate
# Activate (macOS/Linux)
source venv/bin/activate
# Install Flask
pip install flask flask-wtf flask-sqlalchemy python-dotenv
Flask Extensions
Essential Flask extensions youβll learn:
- Flask-WTF - Form handling and CSRF protection
- Flask-SQLAlchemy - Database ORM
- Flask-Login - User session management
- Flask-Mail - Email sending
- Flask-Migrate - Database migrations
HTTP Methods
Understanding HTTP is crucial for web development:
@app.route('/user/<int:user_id>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def user_operations(user_id):
if request.method == 'GET':
# Show user
return f"User {user_id}"
elif request.method == 'POST':
# Create new user
return "User created"
elif request.method == 'PUT':
# Update user
return f"User {user_id} updated"
elif request.method == 'DELETE':
# Delete user
return f"User {user_id} deleted"
Security Best Practices
Flask applications need security:
- CSRF Protection - Prevent cross-site request forgery
- Input Validation - Never trust user input
- SQL Injection Prevention - Use ORM, not raw SQL
- XSS Protection - Escape user content in templates
- Secure Sessions - Use secure cookies and secrets
Deployment
Development vs Production
# config.py
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///app.db'
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
class ProductionConfig(Config):
# Production settings
pass
WSGI Server
# run.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
Practice Projects
Project 1: Personal Blog
Build a blog with:
- Article listing and detail pages
- Markdown content support
- Comment system
- Admin panel for content management
Project 2: Task Manager
Create a todo application with:
- User registration and login
- Task creation, editing, deletion
- Categories and priorities
- Due dates and reminders
Project 3: Recipe Manager
Develop a recipe sharing site with:
- Recipe submission and editing
- Ingredient lists and instructions
- User ratings and reviews
- Search and filtering
Project 4: Weather Dashboard
Build a weather application with:
- Location-based weather data
- Interactive charts and graphs
- Weather API integration
- Favorite locations
Next Steps
After this module, youβll be ready for:
- Advanced Web Development - REST APIs, microservices
- Frontend Integration - JavaScript frameworks
- Deployment - Docker, cloud platforms
- Data Science - Web interfaces for data applications
Getting Started
Begin with Flask Basics to create your first web application. Weβll start simple and build up to complex, real-world applications.
Letβs build some websites! π