Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Flask Documentation

A lightweight Python web framework — routes, Jinja templates, SQLAlchemy and REST APIs; add only what you need.

Flask is a lightweight Python web framework ("micro-framework"). The core gives you routing, requests/responses, templates (Jinja2) and a development server — and you add only what you need (database, auth, forms) through extensions. It's great for small APIs, ML model serving, prototypes and learning how web backends work.

1. Introduction & Installation

python -m venv venv
venv\Scripts\activate          # Windows  (source venv/bin/activate on macOS/Linux)
pip install flask
# app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Flask!"

if __name__ == "__main__":
    app.run(debug=True)
flask --app app run --debug     # or: python app.py

Output:

 * Serving Flask app 'app'
 * Debug mode: on
 * Running on http://127.0.0.1:5000

Debug mode gives auto-reload and an interactive error page. Never enable it in production.

⚠️ Common error: Address already in use — another app uses port 5000 (on macOS, AirPlay Receiver does). Use flask run --port 5001.

2. Routing

@app.route("/about")
def about():
    return "About Codify"

@app.route("/users/<username>")
def profile(username):
    return f"Profile of {username}"

@app.route("/notes/<int:note_id>")
def note(note_id):                       # converted to int; /notes/abc → 404
    return f"Note #{note_id}"

@app.route("/notes", methods=["GET", "POST"])
def notes():
    ...

# shortcut decorators (Flask 2+)
@app.get("/ping")
def ping():
    return {"ok": True}                  # dicts become JSON automatically

Converters: string (default), int, float, path, uuid.

Build URLs from function names:

from flask import url_for, redirect
url_for("profile", username="asha")      # "/users/asha"
return redirect(url_for("home"))

3. Request & Response

from flask import request, jsonify, abort, make_response

@app.post("/api/notes")
def create_note():
    data = request.get_json(silent=True) or {}          # JSON body
    title = (data.get("title") or "").strip()
    if len(title) < 3:
        return jsonify(error="Title must be at least 3 characters"), 400
    return jsonify(id=1, title=title), 201

@app.get("/search")
def search():
    q = request.args.get("q", "")                      # query string ?q=
    page = request.args.get("page", 1, type=int)
    return {"q": q, "page": page}
request Meaning
request.method "GET", "POST"…
request.args query string
request.form HTML form fields
request.get_json() JSON body
request.files uploaded files
request.headers, request.cookies headers, cookies

Responses: return a string, a dict/list (JSON), a tuple (body, status, headers), or make_response(...). abort(404) stops with an error.

4. Templates (Jinja2)

Templates live in a templates/ folder.

<!-- templates/base.html -->
<!doctype html>
<html>
<head><title>{% block title %}Codify{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head>
<body>{% block content %}{% endblock %}</body>
</html>
<!-- templates/notes.html -->
{% extends "base.html" %}
{% block content %}
  <h1>{{ heading }}</h1>
  <ul>
  {% for n in notes %}
    <li>{{ loop.index }}. {{ n.title | title }}</li>
  {% else %}
    <li>No notes yet</li>
  {% endfor %}
  </ul>
  {% if user %}<p>Welcome, {{ user }}</p>{% endif %}
{% endblock %}
from flask import render_template

@app.get("/notes")
def notes_page():
    return render_template("notes.html", heading="All notes", notes=[{"title": "graphs"}], user="Asha")

Output is auto-escaped (XSS-safe). Static files go in static/.

5. Forms, Sessions & Flash Messages

from flask import session, flash

app.secret_key = os.environ["SECRET_KEY"]        # needed for sessions and flash

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        user = find_user(email)
        if user and check_password_hash(user.password, password):
            session["user_id"] = user.id               # signed cookie
            flash("Logged in!")
            return redirect(url_for("home"))
        flash("Wrong email or password")
    return render_template("login.html")

@app.get("/logout")
def logout():
    session.clear()
    return redirect(url_for("home"))
{% for msg in get_flashed_messages() %}<p class="flash">{{ msg }}</p>{% endfor %}

Flask's default session is a signed cookie — users can read it but not change it, so don't store secrets in it. For forms with CSRF protection use Flask-WTF.

Passwords: from werkzeug.security import generate_password_hash, check_password_hash.

6. Database with Flask-SQLAlchemy

pip install flask-sqlalchemy flask-migrate
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from datetime import datetime, timezone

app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///codify.db")
db = SQLAlchemy(app)
migrate = Migrate(app, db)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    notes = db.relationship("Note", backref="author", lazy=True)

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    body = db.Column(db.Text, default="")
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))

    def to_dict(self):
        return {"id": self.id, "title": self.title, "body": self.body}
flask --app app db init       # once
flask --app app db migrate -m "create notes"
flask --app app db upgrade

CRUD:

note = Note(title="Heaps", user_id=1)
db.session.add(note)
db.session.commit()

Note.query.get_or_404(5)                                  # classic API
db.session.execute(db.select(Note).filter_by(user_id=1)).scalars().all()   # SQLAlchemy 2.x style
db.paginate(db.select(Note).order_by(Note.id.desc()), page=2, per_page=20)

note.title = "Heaps & PQ"; db.session.commit()
db.session.delete(note); db.session.commit()

7. Building a REST API

@app.get("/api/notes")
def list_notes():
    q = request.args.get("q", "")
    stmt = db.select(Note).where(Note.title.ilike(f"%{q}%")).order_by(Note.created_at.desc())
    return [n.to_dict() for n in db.session.execute(stmt).scalars()]

@app.get("/api/notes/<int:id>")
def get_note(id):
    return db.get_or_404(Note, id).to_dict()

@app.post("/api/notes")
@login_required_api
def add_note():
    data = request.get_json() or {}
    if not data.get("title"):
        return {"error": "title is required"}, 400
    note = Note(title=data["title"], body=data.get("body", ""), user_id=g.user_id)
    db.session.add(note); db.session.commit()
    return note.to_dict(), 201

@app.delete("/api/notes/<int:id>")
@login_required_api
def delete_note(id):
    db.session.delete(db.get_or_404(Note, id)); db.session.commit()
    return "", 204

A simple token decorator:

from functools import wraps
from flask import g
import jwt

def login_required_api(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        token = request.headers.get("Authorization", "").removeprefix("Bearer ")
        try:
            g.user_id = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"])["id"]
        except jwt.PyJWTError:
            return {"error": "Please log in"}, 401
        return fn(*args, **kwargs)
    return wrapper

CORS for a React front end: pip install flask-cors → CORS(app, origins=["http://localhost:5173"]).

8. Blueprints & the Application Factory

Split a growing app into blueprints and create the app in a function (easier testing and config):

codify/
├── __init__.py        ← create_app()
├── extensions.py      ← db = SQLAlchemy()
├── models.py
├── auth/routes.py     ← auth blueprint
└── notes/routes.py    ← notes blueprint
# codify/notes/routes.py
from flask import Blueprint
bp = Blueprint("notes", __name__, url_prefix="/api/notes")

@bp.get("/")
def list_notes(): ...

# codify/__init__.py
from flask import Flask
from .extensions import db

def create_app(config=None):
    app = Flask(__name__)
    app.config.from_mapping(SECRET_KEY="dev", SQLALCHEMY_DATABASE_URI="sqlite:///codify.db")
    if config: app.config.update(config)
    db.init_app(app)
    from .notes.routes import bp as notes_bp
    app.register_blueprint(notes_bp)
    return app
flask --app codify run --debug

9. Error Handling, File Uploads & Deployment

@app.errorhandler(404)
def not_found(e):
    return {"error": "Not found"}, 404

@app.errorhandler(500)
def server_error(e):
    return {"error": "Something went wrong"}, 500

File uploads:

from werkzeug.utils import secure_filename
app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024         # 2 MB limit

@app.post("/upload")
def upload():
    f = request.files.get("file")
    if not f or not f.filename.lower().endswith((".png", ".jpg", ".jpeg")):
        return {"error": "Upload a PNG or JPG"}, 400
    f.save(os.path.join("uploads", secure_filename(f.filename)))
    return {"ok": True}, 201

Production:

pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 "codify:create_app()"      # Linux/macOS
pip install waitress && waitress-serve --port=8000 --call codify:create_app   # Windows

Put Nginx in front, keep secrets in environment variables, use PostgreSQL in production.

10. Advanced Concepts

  • Application and request context: current_app, g (per-request storage), request and session are context-local proxies — they work only inside a request (or with app.app_context():).
  • Hooks: @app.before_request, @app.after_request, @app.teardown_appcontext.
  • Configuration: app.config.from_object(Config), from_prefixed_env() reads FLASK_* environment variables.
  • Testing:
def test_ping():
    app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite://"})
    client = app.test_client()
    assert client.get("/ping").get_json() == {"ok": True}
  • Useful extensions: Flask-Login (sessions), Flask-JWT-Extended, Flask-WTF (forms + CSRF), Flask-Limiter (rate limits), Flask-Caching, Flask-Mail, Flask-SocketIO.
  • Async: async def views work (pip install flask[async]), but Flask stays WSGI; for heavy async APIs consider FastAPI or Quart.
  • Serving ML models: load the model once at start-up, expose POST /predict that validates input and returns JSON.
model = joblib.load("model.pkl")

@app.post("/predict")
def predict():
    features = request.get_json()["features"]
    return {"prediction": model.predict([features]).tolist()[0]}

11. Examples with Output

Example 1 — Dynamic route

@app.get("/square/<int:n>")
def square(n):
    return {"n": n, "square": n * n}
curl http://127.0.0.1:5000/square/12
{
  "n": 12,
  "square": 144
}

Example 2 — Query parameters with defaults

curl "http://127.0.0.1:5000/search?q=heap"
{
  "page": 1,
  "q": "heap"
}

(Flask sorts JSON keys alphabetically, and pretty-prints JSON in debug mode — without --debug it is one compact line.)

Example 3 — Validation error

curl -X POST http://127.0.0.1:5000/api/notes -H "Content-Type: application/json" -d "{}"
{
  "error": "Title must be at least 3 characters"
}

12. Practice Problems

  1. Build a to-do app with Jinja templates: add, complete and delete tasks stored in SQLite.
  2. Turn it into a JSON API with GET/POST/PATCH/DELETE and proper status codes.
  3. Add user registration and login with hashed passwords and sessions (or Flask-Login).
  4. Restructure the app with blueprints and an application factory.
  5. Add Flask-Migrate and change a model with a migration.
  6. Serve a scikit-learn model at POST /predict with input validation.
  7. Add rate limiting to the login route with Flask-Limiter.
  8. Write pytest tests with the test client and deploy with Gunicorn.

13. Interview Questions

1. Flask vs Django? Flask is minimal and flexible — you choose the ORM, auth and structure. Django includes everything (ORM, admin, auth) with conventions. Flask suits small services/APIs; Django suits larger full-featured sites.

2. What is WSGI? The Python standard interface between web servers (Gunicorn, uWSGI) and web apps (Flask, Django).

3. What are blueprints? A way to organise routes, templates and static files into modules registered on the app.

4. What is the application factory pattern? Creating the app inside create_app() so you can build several instances with different configs (testing, production) and avoid circular imports.

5. What is g in Flask? A per-request storage object for data such as the current user or DB connection.

6. How do sessions work in Flask? Data is stored in a cookie signed with SECRET_KEY; the client can see it but can't modify it without detection.

7. How do you handle errors? @app.errorhandler(code_or_exception) returning a response; abort(code) to raise.

8. Why not use app.run() in production? The built-in server is single-process and not designed for security or performance; use Gunicorn/Waitress behind Nginx.

9. How do you prevent SQL injection in Flask? Use the ORM or parameterised queries — never build SQL with string formatting.

10. What does jsonify do? Converts data to a JSON response with the right Content-Type; returning a dict does the same in modern Flask.

14. Cheat Sheet & References

App and routes

from flask import Flask, request, jsonify, render_template, redirect, url_for, abort
app = Flask(__name__)
@app.get("/items/<int:id>")
@app.post("/items")
@app.route("/x", methods=["GET", "POST"])
return {"ok": True}, 201

Request data

request.args.get("q", "")
request.args.get("page", 1, type=int)
request.form["email"]
request.get_json(silent=True) or {}
request.files["file"]
request.headers.get("Authorization")

Database (Flask-SQLAlchemy)

db = SQLAlchemy(app)
db.session.add(obj); db.session.commit()
db.get_or_404(Note, id)
db.session.execute(db.select(Note).filter_by(user_id=1)).scalars().all()
db.session.delete(obj); db.session.commit()

CLI

flask --app app run --debug
flask --app app db init
flask --app app db migrate -m "msg"
flask --app app db upgrade
gunicorn -w 4 "app:app"

Official documentation