Module 28 - Flask Basics
Flask is a lightweight micro web framework for Python that makes it easy to build web applications quickly.
1. Introduction to Flask
Installation
pip install Flask
Why Flask?
✅ Lightweight and flexible
✅ Easy to learn
✅ Great for small to medium projects
✅ RESTful request dispatching
✅ Built-in development server
2. Hello World
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Run: python app.py → Visit http://127.0.0.1:5000/
3. Routing
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Home Page'
@app.route('/about')
def about():
return 'About Page'
# Dynamic routes
@app.route('/user/<username>')
def user_profile(username):
return f'Profile: {username}'
# Type constraints
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post ID: {post_id}'
if __name__ == '__main__':
app.run(debug=True)
4. Templates
templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome, {{ name }}!</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html',
title='Home',
name='Alice',
items=['Python', 'Flask', 'Web Dev'])
if __name__ == '__main__':
app.run(debug=True)
5. Forms and User Input
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username == 'admin' and password == 'secret':
return redirect(url_for('dashboard'))
else:
return 'Invalid credentials'
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
return 'Welcome to Dashboard!'
if __name__ == '__main__':
app.run(debug=True)
Summary
✅ Flask is a micro web framework
✅ Routes map URLs to Python functions
✅ Jinja2 templates for HTML rendering
✅ Built-in development server
✅ Easy form handling
Next Steps
In Module 29, you'll learn:
- FastAPI framework
- Building REST APIs
- Automatic API documentation
- Pydantic models
Practice Exercises
- Create a simple blog with home, about, and contact pages
- Build a todo list app with add/delete functionality
- Implement user registration and login system
- Create a portfolio website with Flask
- Build a simple REST API for a todo app :::