Skip to content
Tutorials Center
My learning

Topics

Flask Tutorial

Learn Flask 3 from your first route to templates, forms, databases, blueprints, authentication, REST APIs, testing and deployment. 72 lessons with live examples, quizzes and projects.

Start learning →

of lessons completed

Getting Started

  1. 1 What Is Flask? Learn what Flask is, how WSGI connects Python to the web, why a micro-framework is useful, how Flask compares with Django and FastAPI, and what you will build.
  2. 2 Setup and Your First App Install Flask in a virtual environment, create your first Flask app with routes, and send requests to it with the test client. Includes live, runnable examples.
  3. 3 How a Request Flows Through Flask Follow one request through Flask: the WSGI environ, URL matching, the app and request contexts, hooks and the response object. Runnable examples included.
  4. 4 Project Layout and the flask Command Organize a Flask project from a single file to a package with an app factory. Learn the flask command, --debug, .flaskenv, custom CLI commands and the instance folder.

Routing and Views

  1. 5 Routes and HTTP Methods Learn how Flask routes work, how to accept GET and POST with the methods argument, use the app.get and app.post shortcuts, and understand 405 Method Not Allowed.
  2. 6 URL Variables and Converters Capture values from Flask URLs with variable rules, use the int, float, string, path and uuid converters, write your own converter and control trailing slashes.
  3. 7 Building URLs with url_for Learn how Flask's url_for builds URLs from endpoint names, fills in URL variables, adds query strings and anchors, makes external links and finds static files.
  4. 8 Responses, Status Codes and Headers Learn everything a Flask view can return: strings, dicts, tuples, make_response, jsonify, redirects, status codes, headers and cookies on the response.
  5. 9 The Request Object Learn how to read everything a client sends to a Flask view: query strings, form fields, JSON bodies, headers, cookies, uploaded files, and how the request context works.
  6. 10 Error Handling and Custom Error Pages Learn to raise HTTP errors with abort, write custom 404 and 500 pages with errorhandler, return JSON errors for APIs, and handle your own exception classes.
  7. 11 Subdomains and Host Matching Serve api.example.com, admin.example.com and per-customer subdomains from one Flask app. Learn SERVER_NAME, subdomain routes, host_matching, url_for across hosts and local testing.
  8. 12 Streaming Responses and Server-Sent Events Stream data from Flask with generators, stream_with_context, large CSV downloads and Server-Sent Events. Learn the SSE format, the browser EventSource API and what to watch out for in production.

Templates with Jinja

  1. 13 Jinja Templates Basics Learn the basics of Jinja templates in Flask: render_template, passing variables, expressions, filters, automatic HTML escaping and how Flask finds template files.
  2. 14 Loops and Conditionals in Templates Learn Jinja control flow in Flask templates: for loops with the loop variable, for-else for empty lists, if/elif/else, whitespace control and reusable macros.
  3. 15 Template Inheritance and Includes Build one layout and reuse it everywhere. Learn Jinja extends, block, super(), include, import and macros in Flask, with runnable in-memory templates.
  4. 16 Filters, Tests and Custom Helpers Format data in Jinja with built-in filters and tests, then write your own with template_filter, template_test, context processors and template globals in Flask.
  5. 17 Static Files and Assets Serve CSS, JavaScript and images from Flask's static folder, build URLs with url_for, understand caching headers, add cache busting and use send_from_directory.
  6. 18 Styling Flask Apps with Bootstrap and Bootstrap-Flask Style a Flask app with Bootstrap 5. Load it from a CDN or locally, build a responsive base template, and use Bootstrap-Flask macros to render forms, flash messages, navigation and tables.

Forms and User Input

  1. 19 Handling HTML Forms Learn how Flask receives HTML form data. Read request.form, handle GET and POST in one view, work with checkboxes and lists, and apply Post/Redirect/Get.
  2. 20 Validation with WTForms Define forms as Python classes with Flask-WTF and WTForms. Add validators, custom checks, CSRF protection, render fields and errors, and test with the client.
  3. 21 Validating Input Without Libraries Validate Flask form input with plain Python. Build reusable check functions, collect errors in a dict, re-render forms with the user's input and flash success.
  4. 22 Flash Messages Learn how Flask flash messages show a one-time notice after a redirect, how categories work, why SECRET_KEY is required, and how to render flashes in a layout.
  5. 23 File Uploads Accept file uploads in Flask safely: read request.files, clean names with secure_filename, cap size with MAX_CONTENT_LENGTH, check types and choose storage.

State: Sessions and Cookies

  1. 24 Cookies Learn to set, read and delete cookies in Flask, what HttpOnly, Secure, SameSite, Max-Age and Path do, and how the test client's cookie jar works.
  2. 25 Sessions Learn how Flask sessions keep per-user data in a signed cookie, why SECRET_KEY matters, how permanent sessions work and what you should never store in one.

Databases

  1. 26 Using sqlite3 with Flask Use sqlite3 in a Flask app: one connection per request with g, closing it in teardown_appcontext, dict-like rows and SQL injection prevention.
  2. 27 Flask-SQLAlchemy Models Define tables as Python classes with Flask-SQLAlchemy 3 and SQLAlchemy 2 style Mapped columns, create the schema, then add, query and roll back with db.session.
  3. 28 Queries and CRUD Views Query a database from Flask with SQLAlchemy 2 select(), then build create, read, update and delete views with get_or_404, redirects and pagination.
  4. 29 Raw SQL with SQLAlchemy in Flask Run hand-written SQL in Flask-SQLAlchemy with text() and db.session.execute. Bind parameters safely, read rows as mappings, map results to ORM models, and know when to leave the ORM.
  5. 30 Relationships Model one-to-many and many-to-many relationships in Flask-SQLAlchemy with back_populates, understand lazy loading, and fix the N+1 problem with selectinload.
  6. 31 Migrations with Flask-Migrate Learn how database migrations work with Flask-Migrate and Alembic: the flask db commands, upgrade and downgrade, and how schema evolution works in plain SQL.
  7. 32 Flask with MongoDB (PyMongo) Use MongoDB from Flask with PyMongo. Connect, insert and query documents, handle ObjectId in URLs and JSON, update and delete safely, add indexes, and test with mongomock.
  8. 33 Flask with PostgreSQL and MySQL Move a Flask app from SQLite to PostgreSQL or MySQL. Choose a driver, build a safe SQLAlchemy URL, tune the connection pool, run the database in Docker, and avoid dialect traps.

Structure and Configuration

  1. 34 The Application Factory Learn the Flask application factory pattern: write create_app, set up extensions with init_app, give tests their own config and run several apps side by side.
  2. 35 Blueprints Learn how Flask blueprints split an app into modules: url_prefix, endpoint names like blog.index, blueprint templates and static files, and error handlers.
  3. 36 Configuration and Environments Configure Flask the right way: app.config, config classes, from_object, from_prefixed_env, the instance folder, secret keys and twelve-factor style environments.
  4. 37 Hooks, Application Context and g Run code before and after every request with Flask hooks, understand current_app and g, listen to signals, and add your own flask commands tested with test_cli_runner.
  5. 38 WSGI Middleware in Flask Wrap a Flask app in WSGI middleware. Write a timing middleware class, fix client IPs with ProxyFix, mount apps with DispatcherMiddleware, and learn when to use Flask hooks instead.
  6. 39 Sending Email with Flask-Mail Send email from Flask with Flask-Mail. Configure SMTP, build plain and HTML messages, add attachments, send in the background, test with record_messages and avoid header injection.
  7. 40 Flask-Admin and Flask-Babel Add a database admin panel with Flask-Admin ModelView and lock it down, then translate your app and format dates, numbers and currencies for each locale with Flask-Babel.

Authentication and Security

  1. 41 Password Hashing Learn why passwords must be hashed, not encrypted, how salts work, and how to use Werkzeug's generate_password_hash and check_password_hash safely in Flask.
  2. 42 Building a Login System Build a complete Flask login system from scratch with hashed passwords, session-based authentication, a login_required decorator and safe redirects after login.
  3. 43 Flask-Login Use the Flask-Login extension to manage sessions the easy way. Learn LoginManager, user_loader, UserMixin, login_user, current_user, remember me and unauthorized handlers.
  4. 44 Roles and Permissions Decide what each logged-in user may do. Build role decorators, ownership checks and permission maps in Flask, and return clean 401 and 403 responses.
  5. 45 Web Security Essentials Learn the web attacks every Flask developer must stop. Covers XSS and autoescape, SQL injection, CSRF tokens, secure cookies, security headers, CORS and open redirects.
  6. 46 Social Login with OAuth (Authlib) Add "Sign in with Google" to Flask. Understand the OAuth 2 authorization code flow, the state parameter, token exchange and account linking, then wire it up with Authlib.

REST APIs

  1. 47 Building JSON APIs Build a JSON API with Flask. Learn jsonify, request.get_json, the right status codes, a consistent error format and simple content negotiation.
  2. 48 Designing a REST API Design a clean REST API in Flask. Learn resources and URLs, HTTP verbs, idempotency, PUT vs PATCH, pagination, filtering, sorting and API versioning.
  3. 49 Class-Based Views and MethodView Organize Flask endpoints as classes. Learn View, dispatch_request, as_view, MethodView, decorators and a reusable pattern for REST API resources.
  4. 50 Flask-RESTful and Flask-RESTX Resources Build REST APIs with Flask-RESTful Api and Resource classes, parse input with reqparse, shape output with fields, then see what Flask-RESTX adds, and when plain MethodView is enough.
  5. 51 Validation and Serialization Validate incoming JSON and shape outgoing JSON in Flask. Learn schemas with Pydantic, clear 422 error responses, partial updates and hiding private fields.
  6. 52 API Authentication with Tokens Secure a Flask API with bearer tokens. Learn the Authorization header, signed tokens with itsdangerous, how JWT works, 401 vs 403 and rate limiting.

Testing, Quality and Production

  1. 53 Testing Flask Apps with pytest Test Flask applications with pytest. Learn test_client, fixtures for the app factory and a test database, sessions, JSON, redirects, CLI commands and parametrize.
  2. 54 Logging and Debugging Learn how to log from a Flask app with app.logger, configure levels, handlers and formats, add request details to every line, and track errors in production.
  3. 55 Performance and Caching Make a Flask app faster with HTTP caching headers, ETags and 304 responses, an application cache, fewer database queries, indexes and profiling.
  4. 56 Async Views and Background Work Understand async def views in Flask, when threads or worker processes help, and how task queues like Celery and RQ move slow work out of the request.
  5. 57 Deployment Put a Flask app into production with gunicorn, an nginx reverse proxy, Docker, ProxyFix, environment variables and a health check endpoint.

Advanced

  1. 58 Real-Time Apps with WebSockets (Flask-SocketIO) Build real-time Flask features with Flask-SocketIO. Learn events, emit and broadcast, rooms, acknowledgements, the browser client, and how to test a chat server without a browser.

Projects

  1. 59 Project: A Blog Build a complete blog with Flask in three stages. Use an app factory, a blueprint, SQLAlchemy models, Jinja templates, CRUD views, pagination and tests.
  2. 60 Project: A Todo REST API Build a JSON todo API with Flask and SQLite. Add validation, consistent errors, pagination, signed bearer tokens, per-user data and automated tests.
  3. 61 Project: A URL Shortener Build a URL shortener in Flask: base62 short codes, URL validation, 302 redirects, atomic click counts, a stats endpoint and a rate limiter, all tested in the browser.
  4. 62 Project: Users and Login Build a complete Flask account system: registration, hashed passwords, session login, CSRF tokens, flash messages, safe redirects and admin-only pages, all tested.
  5. 63 Project: A Mini Bookshop Build a small Flask online shop with Flask-SQLAlchemy: a book catalog, a session-based cart, an atomic checkout that protects stock, and orders with relationships.
  6. 64 Project: Wikipedia and Weather Search App Build a Flask app that calls other websites' APIs. Use requests with timeouts, handle failures with clear 502 and 504 responses, cache results with a TTL and test it without the network.
  7. 65 Project: Web Scraping API Build a Flask API that extracts data from web pages. Parse HTML with BeautifulSoup, respect robots.txt, block SSRF with a host allowlist, cache results and return clean JSON.
  8. 66 Project: Single-Page Portfolio Site Build a one-page portfolio with Flask. Use template inheritance and data-driven sections, static CSS, a validated contact form with CSRF and spam protection, and SEO tags.
  9. 67 Deploying a Machine Learning Model with Flask Serve a scikit-learn model with Flask. Train and save it with joblib, load it once at startup, build a prediction form and a JSON API, validate inputs, test it and plan for production.
  10. 68 Project: A Sentiment Analysis Web App Build a Flask app that scores short texts as positive, neutral or negative, stores them in SQLite and serves summary data for a chart. Then swap in a real model.
  11. 69 Charts and Dashboards in Flask (Chart.js, Matplotlib, Bokeh) Build a Flask dashboard. Serve aggregated data as JSON for Chart.js, render plots on the server with Matplotlib, embed data safely with tojson, and compare Plotly and Bokeh.

Practice and Review

  1. 70 Practice Exercises with Solutions 14 hands-on Flask exercises with solutions on routing, templates, forms, sessions, cookies, databases, error handling, blueprints and JSON APIs. Run them in your browser.
  2. 71 Interview Questions 39 common Flask interview questions with concise answers: WSGI, contexts, blueprints, sessions, security, testing, concurrency and deployment.
  3. 72 Flask Cheat Sheet A one-page Flask 3 cheat sheet with routing, request and response, Jinja, sessions, configuration, blueprints, SQLAlchemy, testing and deployment snippets.