🌍 Python · subject
Python Flask Syllabus
The Flask syllabus for Python in full: 6 chapters, 17 topics and 44 sub-topics, every one listed below, plus 50 Flask flashcards with answers.
Flask syllabus: all 6 chapters
Expand any chapter to see its topics and sub-topics.
-
Introduction to Flask
3 topics- Overview
- What is Flask?
- History of Flask
- Flask vs Other Frameworks
- Installation
- Setting up a Virtual Environment
- Installing Flask via pip
- First Flask Application
- Creating a Simple Application
- Running the Application
- Understanding Flask Application Structure
- Overview
-
Core Concepts
3 topics- Routing
- URL Routing
- Variable Rules
- HTTP Methods
- Templates
- Jinja2 Templating Engine
- Template Inheritance
- Rendering Templates
- Template Context
- Static Files
- Serving Static Files
- Configuring Static File Paths
- Routing
-
Advanced Concepts
3 topics- Forms
- Handling Forms
- WTForms Integration
- Form Validation
- Database Integration
- SQLAlchemy
- Flask-SQLAlchemy
- Database Migrations with Flask-Migrate
- Authentication
- Flask-Login
- User Registration
- User Authentication
- Password Hashing
- Forms
-
Deployment
3 topics- Production Environment
- Configuring for Production
- Using a WSGI Server
- Hosting Options
- Deploying on Heroku
- Deploying on AWS
- Deploying on DigitalOcean
- Containerization
- Dockerizing a Flask Application
- Using Docker Compose
- Production Environment
-
Testing
2 topics- Unit Testing
- Writing Unit Tests
- Using Flask's Testing Client
- Integration Testing
- Setting up Integration Tests
- Testing Application Endpoints
- Unit Testing
-
Best Practices
3 topics- Application Structure
- Organizing Flask Projects
- Blueprints
- Configuration Management
- Environment-based Configuration
- Using Config Files
- Security
- Preventing Common Vulnerabilities
- Using Flask-Security
- Application Structure
Python Flask flashcards — 50 questions with answers
What is Flask and how is it classified among web frameworks?
Flask is a lightweight WSGI web framework for Python. It is classified as a 'micro-framework' because it keeps its core minimal (routing + request/response) and leaves features like database access, form validation, and authentication to extensions rather than bundling them.
On which two core libraries is Flask built?
Flask is built on Werkzeug (a WSGI utility library that handles requests, responses, and routing) and Jinja2 (the template engine for rendering HTML).
What does WSGI stand for and what is its role relative to Flask?
WSGI = Web Server Gateway Interface. It is the standard Python interface between web servers and web applications. Flask is a WSGI application; a WSGI server (e.g. Gunicorn) calls the Flask app to handle each request.
What is the difference between a micro-framework like Flask and a full-stack framework like Django?
Flask (micro) ships a minimal core and adds functionality via optional extensions, giving flexibility and less convention. Django (full-stack) is 'batteries-included' with a built-in ORM, admin, forms, and auth, enforcing more structure and convention out of the box.
What is the recommended way to install Flask in isolation, and the command to create and activate a virtual environment?
Use a Python virtual environment to isolate dependencies. Create it with `python -m venv venv`, then activate with `source venv/bin/activate` (Linux/macOS) or `venv\Scripts\activate` (Windows). Install Flask with `pip install Flask`.
Why should each Flask project use its own virtual environment?
To isolate package dependencies and versions per project, preventing conflicts between projects and keeping the global Python installation clean and reproducible (capturable via `pip freeze > requirements.txt`).
Write the minimal 'first Flask application' code.
```python from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' ``` Then run with `flask run` or `app.run()`.
What is the purpose of passing `__name__` to `Flask(__name__)`?
`__name__` tells Flask the import name of the application module so it can locate resources like the `templates/` and `static/` folders relative to that module.
What are the two common ways to start the Flask development server?
1) The CLI: set `FLASK_APP=app.py` then run `flask run`. 2) In code: call `app.run()` inside a `if __name__ == '__main__':` guard. Add `debug=True` (or `FLASK_DEBUG=1`) to enable the debugger and auto-reload.
What does enabling debug mode (`debug=True`) do in Flask?
It activates the interactive in-browser debugger (showing tracebacks) and the automatic reloader that restarts the server on code changes. It must be turned OFF in production for security.
What is routing in Flask and which decorator defines a route?
Routing maps a URL path to a Python view function. The `@app.route('/path')` decorator binds a URL rule to the function that should handle requests to that URL.
How do you define a dynamic URL segment with a type converter in a Flask route?
Use angle brackets with an optional converter: `@app.route('/user/<int:user_id>')`. Built-in converters include `string` (default), `int`, `float`, `path`, and `uuid`. The captured value is passed as a function argument.
How do you restrict a Flask route to specific HTTP methods?
Pass the `methods` list to the decorator: `@app.route('/submit', methods=['GET', 'POST'])`. By default a route only accepts GET (and implicitly HEAD/OPTIONS).
What does Flask's `url_for()` function do, and why is it preferred over hardcoding URLs?
`url_for('endpoint', **values)` builds a URL by the view function's name (endpoint) rather than a literal path. It is preferred because it survives route changes, handles escaping, and correctly builds static/blueprint URLs.
Which template engine does Flask use, and what function renders a template?
Flask uses Jinja2. Templates are rendered with `render_template('page.html', **context)`, which looks for the file in the `templates/` folder and passes context variables to it.
In Jinja2, what is the difference between `{{ ... }}` and `{% ... %}`?
`{{ expression }}` outputs (prints) the evaluated value into the template. `{% statement %}` is for control logic like `if`, `for`, `block`, and `extends` that produces no direct output.
How does Jinja2 template inheritance work?
A base template defines overridable regions with `{% block content %}{% endblock %}`. A child template starts with `{% extends 'base.html' %}` and redefines those blocks. This promotes DRY layouts (shared header/footer).
What is autoescaping in Jinja2 and why does it matter for security?
Jinja2 automatically escapes HTML special characters (`<`, `>`, `&`, quotes) in `{{ }}` output for `.html` templates, preventing cross-site scripting (XSS). Use the `|safe` filter only on trusted content to bypass it.
Where does Flask serve static files from by default, and how do you reference them in a template?
From the `static/` folder, served at the `/static/` URL by default. Reference them in templates with `url_for('static', filename='style.css')` rather than a hardcoded path.
What library is commonly used for forms in Flask, and what key feature does it provide?
Flask-WTF (a wrapper around WTForms). It provides declarative form classes, server-side validation, and built-in CSRF protection for form submissions.
Show the other 30 Flask flashcards
In Flask, how do you access submitted form data and URL query parameters?
Form (POST body) data: `request.form['field']` or `request.form.get('field')`. URL query string parameters: `request.args.get('field')`. Both come from the global `request` object imported from flask.
What is CSRF and how does Flask-WTF protect against it?
CSRF (Cross-Site Request Forgery) tricks an authenticated user's browser into submitting unwanted requests. Flask-WTF embeds a per-session secret CSRF token (`{{ form.csrf_token }}`) in forms and validates it on submission, rejecting forged requests.
Which extension provides ORM-based database integration for Flask, and what does it wrap?
Flask-SQLAlchemy. It wraps the SQLAlchemy ORM/toolkit, providing a `db` object, declarative model classes (`db.Model`), and a configured session integrated with the Flask app context.
What configuration key sets the database connection in Flask-SQLAlchemy, and give an example value for SQLite?
`SQLALCHEMY_DATABASE_URI`. Example for SQLite: `'sqlite:///app.db'`. For PostgreSQL: `'postgresql://user:pass@host/dbname'`.
How do you define a model and create the tables with Flask-SQLAlchemy?
Subclass `db.Model` with `db.Column` attributes, then create tables by calling `db.create_all()` (typically inside an application context). For schema changes over time, use Flask-Migrate (Alembic) instead of recreating.
What tool handles database schema migrations in Flask, and what does it wrap?
Flask-Migrate, which wraps Alembic. Typical commands: `flask db init`, `flask db migrate -m "message"`, and `flask db upgrade` to apply version-controlled schema changes.
Which extension manages user login sessions in Flask, and what main object/decorator does it provide?
Flask-Login. It provides the `LoginManager`, the `current_user` proxy, `login_user()`/`logout_user()` functions, and the `@login_required` decorator to protect views.
Why should passwords never be stored in plaintext, and what function pair does Werkzeug provide for hashing?
Plaintext passwords are catastrophic if the database is breached. Werkzeug provides `generate_password_hash(password)` to store a salted hash and `check_password_hash(hash, password)` to verify on login.
What four methods/properties must a Flask-Login user model implement (via UserMixin)?
`is_authenticated`, `is_active`, `is_anonymous`, and `get_id()`. Inheriting from `UserMixin` provides default implementations of all four.
What is the difference between authentication and authorization?
Authentication verifies WHO a user is (identity, e.g. login credentials). Authorization determines WHAT an authenticated user is permitted to do (access control / roles/permissions). Authentication precedes authorization.
Why is Flask's built-in development server unsuitable for production?
It is single-threaded by default, not optimized for performance, lacks robustness/security hardening, and is not designed to handle concurrent production traffic. A dedicated WSGI server should be used instead.
Name two common production WSGI servers used to run Flask apps.
Gunicorn (Green Unicorn) and uWSGI. On Windows, Waitress is also common. These serve the Flask WSGI app with multiple workers for concurrency.
In a production Flask deployment, what is the role of a reverse proxy like Nginx in front of Gunicorn?
Nginx handles incoming HTTP connections, serves static files efficiently, terminates TLS/SSL, load-balances, buffers slow clients, and forwards dynamic requests to the Gunicorn/WSGI server, which runs the Flask app.
What does the formula for sizing Gunicorn workers commonly recommend?
A common rule of thumb is $workers = (2 \times N_{cores}) + 1$, where $N_{cores}$ is the number of CPU cores. This balances CPU utilization against I/O wait.
List several hosting options for deploying a Flask application.
PaaS (Heroku, Render, Railway, PythonAnywhere), IaaS/VPS (AWS EC2, DigitalOcean, Linode), serverless (AWS Lambda + API Gateway via Zappa), and container platforms (AWS ECS/EKS, Google Cloud Run, Kubernetes).
What is the difference between PaaS and IaaS for hosting Flask?
PaaS (Platform-as-a-Service, e.g. Heroku) manages servers, OS, and runtime—you just push code. IaaS (Infrastructure-as-a-Service, e.g. EC2) gives you raw virtual machines you must configure, secure, and maintain yourself. PaaS trades control for convenience.
What is containerization and which tool is most commonly used to containerize Flask apps?
Containerization packages an application with all its dependencies and runtime into a portable, isolated unit (container) that runs consistently across environments. Docker is the most common tool.
What is a Dockerfile and name three typical instructions used when containerizing a Flask app.
A Dockerfile is a text script of instructions to build a container image. Typical instructions: `FROM python:3.x-slim` (base image), `COPY` (add code), `RUN pip install -r requirements.txt` (deps), `EXPOSE` (port), and `CMD ["gunicorn", ...]` (start command).
What is the difference between a Docker image and a Docker container?
An image is a read-only template/blueprint built from a Dockerfile. A container is a running (or stopped) instance of an image—the live, isolated process. You can run many containers from one image.
What is Docker Compose used for in a Flask project?
Docker Compose defines and runs multi-container applications via a `docker-compose.yml` file—e.g. orchestrating the Flask app container together with a database (Postgres) and cache (Redis) containers, with networking and volumes.
What is unit testing, and what does it isolate in a Flask app?
Unit testing verifies a single, smallest piece of logic (a function or method) in isolation, mocking external dependencies. In Flask it targets individual helpers, model methods, or utility functions independent of the HTTP layer.
How do you obtain a test client in Flask for testing routes without a running server?
Call `app.test_client()`, which returns a client you can use to issue requests like `client.get('/')` or `client.post('/login', data={...})` and inspect the response (`response.status_code`, `response.data`).
What is the difference between unit testing and integration testing?
Unit testing checks one component in isolation. Integration testing verifies that multiple components work together correctly—e.g. a request hitting a route, querying the real (or test) database, and rendering a template end-to-end.
Name two popular Python testing frameworks used with Flask and the assertion style each favors.
unittest (standard library, class-based with `self.assertEqual` style assertions) and pytest (function-based, uses plain `assert` statements with rich introspection and fixtures).
What is the Application Factory pattern in Flask and why is it useful?
It is a function (e.g. `def create_app(config):`) that constructs and returns the Flask app, initializing extensions inside it. It enables multiple app instances (e.g. for testing), avoids circular imports, and supports per-environment configuration.
What is a Flask Blueprint and what problem does it solve?
A Blueprint is a way to organize a group of related routes, templates, and static files into a reusable component. It modularizes large applications and lets you register feature areas (e.g. auth, admin) onto the app, avoiding one monolithic file.
List the four main ways to load configuration in Flask.
1) `app.config.from_object('config.Config')` (object/class), 2) `app.config.from_pyfile('config.py')` (file), 3) `app.config.from_envvar('SETTINGS')` (env-referenced file), and 4) `app.config['KEY'] = value` / `from_mapping`. Often combined with environment variables for secrets.
Why are class-based config objects (e.g. Development, Production) a recommended pattern?
They allow a base `Config` class with shared defaults and subclasses (`DevelopmentConfig`, `ProductionConfig`, `TestingConfig`) overriding values like `DEBUG` and database URIs, so the right configuration is selected per environment cleanly.
What is the SECRET_KEY in Flask used for, and how should it be managed?
`SECRET_KEY` cryptographically signs session cookies and CSRF tokens, protecting them from tampering. It must be a long random value, kept secret, and loaded from an environment variable (never hardcoded or committed to version control).
Name three core web security best practices a Flask application should follow.
1) Use HTTPS/TLS and set secure session cookies (`SESSION_COOKIE_SECURE`, `HTTPONLY`, `SAMESITE`). 2) Prevent injection: use the ORM/parameterized queries (SQL injection) and rely on Jinja2 autoescaping (XSS). 3) Enable CSRF protection (Flask-WTF), hash passwords, and disable debug mode in production.
Python Flask FAQ
What is in the Python Flask syllabus?
Python Flask is split into 6 chapters: Introduction to Flask, Core Concepts, Advanced Concepts, Deployment, Testing and Best Practices. Together they contain 17 topics and 44 sub-topics.
How many chapters are in Python Flask?
6 chapters, containing 17 topics and 44 sub-topics. The largest chapter is Introduction to Flask, with 3 topics.
Are there flashcards for Python Flask?
Yes — a 50-card Flask deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.