
Explore chapter 1 of the flask mega-tutorial via the repository. See one commit per chapter, browse commits, and download a zip to copy and paste sections.
Install Python according to your operating system using Homebrew on Mac, Linux package managers, Windows WSL, or Cygwin, then verify a Python 3.5+ interpreter and learn how to exit.
Create a microblog project directory and activate a virtual environment across Unix, Mac, and Windows. Install Flask with pip and verify the installation by importing Flask in a Python session.
Design a scalable Flask microblog by structuring a Python package, configuring an app instance, and mapping routes with decorators to display a hello world page.
Learn to use Flask templates to separate logic from presentation by rendering a page with placeholders via render_template and a fake user.
Explore conditional statements in Flask templates using the Ginger 2 engine to render an alternative title when the title variable is absent, then restore it.
Render a list of blog posts using a Jinja loop in a Flask app, creating mock posts and displaying author and body with dot syntax and html structure.
Implement template inheritance with a base template to share a navigation bar across all pages, define a content block, and extend this base in derived templates like index.
Explore web forms in chapter 3 of the Flask Mega-Tutorial, showing how users provide information to the application and how to set up a microblog with an activated virtual environment.
Install flask-wtf to handle web forms with field validation and CSRF protection, and move configuration to a separate class loaded by app.config.from_object from environment variables.
Create a login form class in flask wdf with username, password, remember me, and submit fields, using data required validators from wtforms to prevent empty submissions.
Create a login form template in Flask WDF, render labeled fields, and protect with a CSRF token using hidden_tag. Use POST for form submissions.
Add a new /login route, instantiate the login form, and render the login template in Flask, then link the form in navigation and run a local test.
Learn to receive form data with a Flask route that handles GET and POST, validates input, flashes a message, and redirects to the index page using the base template.
Improve field validation by displaying per-field error messages beneath inputs when validation fails, using templates to render and style errors for each form field.
Generate links with the url_for function by mapping endpoints to view functions, making navigation maintainable as routes change. Templates access Flask functions automatically, while Python code must import required functions.
Learn to create the microblog database in chapter four by storing users and block posts.
Explore how relational databases store structured content and manage schema changes with migrations using Alembic and Flask-Migrate, installing them in your virtual environment.
Configure flask-sqlalchemy to support sqlite for development and mysql or postgresql for production by building a full database uri and using an environment variable override. Enable migrations and define models.
Create a user model by subclassing flask_sqlalchemy base, with id as primary key and unique, indexed username and email. Include a password hash and a repr for debugging.
Initialize the migration framework, create a migrations directory with the first migration for the users table, and set the Flask app environment variable (microblog.py) to run migrations.
Learn to create and apply your first database migration with flask db migrate and upgrade, including an upgrade and downgrade path and a users table for your new user model.
Apply flask db upgrade and downgrade commands to migrate your database safely, preserving data while tracking migration history, current state, and the head migration.
Develop a post model with id, body, UTC timestamp, and a user id foreign key, then establish a dynamic user-post relationship and migrate the database.
Test and interact with the database by creating users and posts, committing changes, and querying data with filters, ordering, and deletions.
Create a Flask shell context with an app shell context processor to expose symbols like user and post, so starting a Python shell auto-imports the app, db, and models.
Explore chapter five of the Flask Mega-Tutorial as you combine templates, forms, and databases to build the user authentication subsystem.
Learn how to securely hash passwords in a Flask app using generate_password_hash and check_password_hash; store hashes in the user model, understand salts create unique hashes, and verify input during login.
Learn to persist user login state by using the Flask-Login extension to manage per-client sessions, install in a virtual environment, initialize the login manager, and create a login instance.
Learn how to prepare your user model for Flask-Login by applying a mixin base class that adds three attributes and one method, enabling seamless compatibility with the login extension.
Implement a user loader function in flask login that reads the session user id, converts it to an integer, and retrieves the corresponding user object via a database query.
Learn to authenticate users by querying the database for the username, validating the password, and logging in with remember me support, while handling invalid attempts and already logged-in users.
Implement a logout route in Flask, using logout_user to clear the session, then redirect to the index and update the base template to show logout when current_user is not anonymous.
Protect routes with login_required, redirect unauthenticated users to the login page, and validate the next URL argument to stay on a safe relative path.
Connect the logged-in user to templates by using current_user, convert the index page to a protected route, and greet the user in templates while handling login and logout redirects.
Implement a Flask user registration form that uses custom validators to ensure unique username and email and password confirmation, then creates the user, flashes success, and redirects to login.
Pivot from heavy features in chapter six of the Flask mega tutorial to implement the user profile page.
Create a dynamic /user profile route in flask, protected by login_required, fetch the user by username or 404, render a profile template with user and posts.
Explore generating avatar images with Gravatar by hashing emails, lowercasing them, and configuring size and default options, then display avatars on user profiles and posts.
Learn how to reuse a blog post table across pages by moving it into a jinja2 sub-template named underscore_post.html and including it in multiple templates.
Add two profile fields, about me and last seen, to the user model with a migration and UTC default, then display them conditionally on the profile page.
Track each user's last visit time by adding a before_request function in Flask that updates the last_seen timestamp in UTC for authenticated users on every page request.
Create a profile editor with an edit profile form for username and about me, including a 0–140 length validator, get/post routes protected by login, and pre-populated fields that save changes.
Explore chapter seven of the Flask mega-tutorial and learn the options Flask offers for error handling.
Learn how Flask handles not found and internal server errors, view stack traces, diagnose issues like a duplicate username caused by a unique constraint, and implement fixes.
Enable Flask debug mode with the environment variable to view interactive error pages and a Python console, and rely on the reloader for automatic development restarts.
Define custom not found and internal server error pages in Flask using the app.errorhandler decorators, rendering templates with 404 and 500 status codes. Rollback the database session on errors.
Learn to configure an email server via environment variables to send Flask error notifications immediately after a 500 in production, using the Python SMTPHandler and standard logging.
Learn to log a Flask app to a file with a rotating file handler, creating a logs directory, and formatting entries with time, level, message, and source line.
Implement a custom validator in the edit profile form to prevent duplicate usernames in Flask, passing the original username from the route and validating only when the user changes it.
Continue building the app's database and implement the followers feature in Chapter 8 of the Flask Mega-Tutorial.
Explore one-to-many relationships for post ownership, with foreign keys linking posts to authors, plus the author attribute in user models; compare many-to-many and one-to-one via auxiliary tables and constraints.
Represent followers as a self-referential many-to-many relationship on the user entity. Show how a follower user follows many users and is followed by many users.
Add an auxiliary followers table with two foreign keys to model the follower relationship, and define the SQLAlchemy relationship with primary join, secondary join, and lazy dynamic backrefs, then migrate.
Implement following and followers in a Flask app using a self-referential relationship, with follow, unfollow, and is_following methods, and a filter-based query for existence.
Create a timeline by joining the posts and followers tables to fetch posts from followed users. Filter by follower id and order by post timestamp to show newest posts first.
Combine followed posts with the user's own posts using a union to show a complete timeline. Implement the union and order by to sort the combined results.
Develop and run unit tests for the user model using Python's unittest package, employing an in-memory sqlite database and SQLAlchemy to verify password hashing, avatar, and follower features.
Implement follow and unfollow routes with authentication, validating users and preventing self-follow. Update the user profile to show follow links and follower/following counts.
Chapter 9 of the Flask Mega-Tutorial focuses on pagination while guiding the microblog app toward becoming a fully functional application.
Add a home page post form to create blog posts from a 1–140 character body, save with the current user, flash a message, and redirect.
Replace fake blog posts on the home page with real posts by querying followed users and the user's own posts. Render them in the index template.
Create an explorer page with a /explore route for authenticated users to view posts from all users, reuse the index template, hide the submission form, and link authors to profiles.
Add pagination links below the blog list by using the pagination object's next and previous URLs with dynamic query strings, and conditionally rendering them on index and explore templates.
Implement pagination on the user profile page by fetching posts from query string, sorting by newest, paginating with 25 items per page from configuration, and rendering next and previous links.
Learn to implement email-based password recovery in a Flask app by cloning the GitHub repository and using the finished microblog project with migrations and user registration.
Learn to set up Flask-Mail for sending emails and generate recovery links using JWT tokens, by installing Flask-Mail and JWT, initializing the extension, and testing with a local debugging server.
Demonstrate sending an email with Flask-Mail from the Flask shell by constructing a Message with subject, sender, recipients, text and html bodies, then sending via mail.send.
Build a wrapper function in the app's email api module to encapsulate email sending with a send_email function, offering synchronous options and addressing blocking by later threading.
Implement the password reset flow with a reset password request form that collects the email, includes CSRF protection, validates input, sends the reset email, and redirects to login.
Generate and verify secure password reset tokens using JWT in a Flask app, embedding user id and expiration, signing with a secret key to prevent tampering.
Generate a user-specific reset token, render the reset password templates, and send a fully qualified reset email to the user with a link to the reset password route.
Verify the dynamic token in the reset password route from the forgot password email, render a reset form, validate and set the new password, and redirect to login.
Move the email sending to a background thread to avoid blocking requests. Start a thread that runs mail.send with an installed application context and Flask mail configuration.
The Flask Mega-Tutorial is an overarching tutorial for Python beginner and intermediate developers that teaches web development with the Flask framework. The tutorial was born as a series of blog articles, and has been thoroughly revised, updated and expanded as a result of a successful Kickstarter campaign. The concepts that are covered go well beyond Flask, including a wide range of topics Python web developers need to know when writing their own applications.
The goal of the course is to build a nicely featured social blogging web application. Chapter 1 begins with a very simple version of this application that has just a few lines of code. Then, each successive chapter adds a new feature to it. The 23 chapters in this course can be roughly split into two parts: the first 12 chapters are focused on basic web development concepts, while the remaining 11 chapters cover intermediate and advanced techniques. All the code featured in this tutorial is open source, and is available on GitHub. You are welcome to use any of it for your own projects!
This edition of the tutorial includes over 11 hours of video showing how to perform all the steps in detail. For added context, the blog articles from where this tutorial originated are available on Miguel Grinberg's blog.
Important Note: The content in this tutorial was created in 2018 and revised in 2021, so you should expect minor issues due to changes in Python, Flask and other dependencies used. The blog version of this tutorial can be used as guidance to resolve problems.