Welcome back, young web developer! ๐ In Module One, you built your first Flask application and learned the basics of routing, templates, and forms. But your app was missing something important โ data persistence and user accounts. In this module, you will learn how to add a database to your Flask app and create a user authentication system.
A database is like a giant, organized filing cabinet ๐ where your app can store information permanently. Without a database, your app would forget everything every time it restarts. With a database, you can save user profiles, blog posts, comments, and much more.
You will also learn how to let users register and log in to your app. This is called user authentication, and it is the foundation of almost every web application โ from social media to online banking.
By the end of this module, you will have built a fully functional web application with a database and user accounts. Let us dive in! ๐
By the end of this module, you will be able to:
werkzeug.security.Ada had built a simple blog using Flask, but anyone could add or delete posts. She wanted her friends to have their own accounts so they could write their own posts and only edit their own content. She needed a database to store user information and a way to handle login and registration.
Her mentor, Mr. Obi, said, "Ada, you need to add a database and authentication. Flask has great extensions for this. You can use Flask-SQLAlchemy to manage the database and Flask-Login to handle user sessions. And for passwords, you will use hashing to keep them secure."
Ada followed his advice. She defined a User model with
fields for username, email, and password_hash. She created routes for
registration and login, with forms to collect user input. She used
flask-login to manage the logged-in user and protect
certain pages.
"Now my blog is a real web application!" Ada said. Her friends could create accounts, log in, and write their own posts. Ada's app was now secure and user-friendly. And you will learn how to build the same system! ๐ก๏ธ
Definition: A database is a structured collection of data that can be easily accessed, managed, and updated.
Why it is important: Without a database, your application cannot remember data between sessions. A database allows you to store user information, posts, comments, and anything else permanently.
Simple explanation: Imagine you have a notebook where you write down your friends' phone numbers. If you lose the notebook, you lose the information. A database is like a safe, digital notebook that never gets lost and can be searched instantly.
Real-life example: A school stores student records in a database. A bank stores customer accounts in a database.
School example: Your teacher uses a register to track attendance โ that is a simple database.
Home example: Your family might keep a list of contacts on a phone โ that is also a database.
Nigerian example: A bank in Lagos stores customer account information in a database.
Illustration:
DATABASE CONCEPT
+-------------------------------------------------+
| Your Flask App |
| โ |
| Database (SQLite, PostgreSQL, etc.) |
| โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ |
| โ Table: users โ |
| โ โโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโ โ |
| โ โ id โ username โ password โ โ |
| โ โโโโโโผโโโโโโโโโโโผโโโโโโโโโโโโค โ |
| โ โ 1 โ ada โ hashed... โ โ |
| โ โ 2 โ chidi โ hashed... โ โ |
| โ โโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโ โ |
| โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ |
+-------------------------------------------------+
Mini summary: A database stores data permanently so your app can remember information even after it restarts.
Definition: SQLAlchemy is a Python library that provides an ORM (Object-Relational Mapper). An ORM lets you interact with a database using Python objects instead of writing raw SQL queries.
Why it is important: ORMs make database code cleaner, safer, and easier to write. You can think in Python classes instead of SQL tables.
Simple explanation: Imagine you are building a house. Instead of learning how to make bricks and cement, you use pre-made blocks. SQLAlchemy gives you pre-made blocks (Python objects) to build your database.
Real-life example: A developer defines a User
class, and SQLAlchemy automatically creates a users table
in the database.
School example: Your teacher gives you a template (class) to fill in student information; the template is like an ORM model.
Home example: You use a recipe card (class) to store different recipes; each recipe card is like an object.
Nigerian example: A developer uses SQLAlchemy to build a student management system without writing complex SQL queries.
Illustration:
ORM CONCEPT
+-------------------------------------------------+
| Python Class โ SQLAlchemy ORM โ Database |
| (User) (users table) |
| โ |
| user = User(name="Ada") |
| db.session.add(user) |
| db.session.commit() |
| โ SQL: INSERT INTO users (name) VALUES ("Ada") |
+-------------------------------------------------+
Mini summary: SQLAlchemy ORM lets you work with databases using Python classes instead of writing SQL. It makes database code simpler and safer.
Definition: Flask-SQLAlchemy is a Flask extension that adds SQLAlchemy support to Flask. It makes it easy to integrate a database into your Flask app.
Why it is important: Flask-SQLAlchemy handles the connection and session management for you, so you can focus on your models and data operations.
Simple explanation: Think of Flask-SQLAlchemy as a bridge ๐ between your Flask app and the database. It connects them smoothly.
Steps to set up:
pip install flask-sqlalchemySQLAlchemy object.Code example:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///myapp.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Define models here...
with app.app_context():
db.create_all() # Creates tables
Real-life example: A developer configures the database connection string and initializes the ORM.
School example: You set up a new notebook for a subject and label it clearly.
Home example: You organize a shelf for your books, labeling each section.
Nigerian example: A startup in Abuja sets up a PostgreSQL database for their Flask app.
Illustration:
FLASK-SQLALCHEMY SETUP
+-------------------------------------------------+
| app = Flask(__name__) |
| app.config['SQLALCHEMY_DATABASE_URI'] = '...' |
| db = SQLAlchemy(app) |
| โ |
| db.create_all() โ Creates tables |
+-------------------------------------------------+
Mini summary: Flask-SQLAlchemy connects your Flask app to a database. Configure the URI, initialize the object, and create tables.
Definition: A model is a Python class that represents a database table. Each attribute of the class represents a column in that table.
Why it is important: Models define the structure of your data. They tell SQLAlchemy what tables to create and what columns they have.
Simple explanation: Think of a model as a blueprint for a table. It's like a form that you fill out for each record.
How to define a model:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
def __repr__(self):
return f'<User {self.username}>'
Common column types:
db.Integer โ whole numbersdb.String(length) โ text with a maximum lengthdb.Text โ long textdb.DateTime โ date and timedb.Boolean โ True/False
Real-life example: A school defines a Student
model with columns for name, class, and age.
School example: Your teacher creates a registration form with fields for name, age, and class.
Home example: You have a recipe card with fields for name, ingredients, and instructions.
Nigerian example: A bank defines a Customer
model with account_number, name, and balance.
Illustration:
MODEL TO TABLE
+-------------------------------------------------+
| class User(db.Model): |
| id = db.Column(db.Integer, primary_key=True) |
| username = db.Column(db.String(80)) |
| email = db.Column(db.String(120)) |
| password_hash = db.Column(db.String(128)) |
+-------------------------------------------------+
| โ Creates table: |
| CREATE TABLE user ( |
| id INTEGER PRIMARY KEY, |
| username VARCHAR(80), |
| email VARCHAR(120), |
| password_hash VARCHAR(128) |
| ); |
+-------------------------------------------------+
Mini summary: Models are Python classes that define database tables. Each attribute is a column. Use built-in column types to specify the data type.
Definition: CRUD stands for Create, Read, Update, Delete โ the four basic operations on data.
Why it is important: These operations let you manage your data: add new records, retrieve them, change them, and remove them.
Simple explanation: Imagine you have a list of contacts. You can add a new contact (Create), see the list (Read), change a phone number (Update), or remove a contact (Delete). These are CRUD operations.
Examples in SQLAlchemy:
# CREATE
new_user = User(username='ada', email='ada@example.com')
db.session.add(new_user)
db.session.commit()
# READ (all users)
users = User.query.all()
# READ (filter by username)
user = User.query.filter_by(username='ada').first()
# UPDATE
user = User.query.get(1)
user.email = 'newemail@example.com'
db.session.commit()
# DELETE
user = User.query.get(1)
db.session.delete(user)
db.session.commit()
Real-life example: An e-commerce site adds a new product (CREATE), lists all products (READ), updates its price (UPDATE), and removes discontinued products (DELETE).
School example: Your teacher adds a new student to the register (CREATE), checks attendance (READ), changes a student's grade (UPDATE), and removes a student who left (DELETE).
Home example: You add a new recipe (CREATE), view your recipes (READ), change an ingredient (UPDATE), and remove a recipe (DELETE).
Nigerian example: A bank adds a new customer (CREATE), checks their balance (READ), updates their address (UPDATE), and closes an account (DELETE).
Illustration:
CRUD OPERATIONS
+-------------------------------------------------+
| C: db.session.add(obj) โ INSERT |
| R: Model.query.all() โ SELECT * |
| U: update attribute โ UPDATE |
| D: db.session.delete(obj) โ DELETE |
| Always commit: db.session.commit() |
+-------------------------------------------------+
Mini summary: CRUD operations are the foundation of data management. SQLAlchemy provides methods to perform them using Python objects.
Definition: User authentication is the process of verifying that a user is who they claim to be. It usually involves a username and password.
Why it is important: Authentication protects your application and its data. It ensures that only authorized users can access certain features, like writing posts, viewing personal information, or making purchases.
Simple explanation: Imagine you have a diary with a lock ๐. Only you and trusted friends have the key. Authentication is like that lock โ it keeps out unwanted visitors.
Real-life example: Online banking requires a username and password to log in. Social media platforms use authentication to protect user accounts.
School example: Your school has a gate with a security guard who checks ID cards before letting people in.
Home example: Your phone has a PIN or fingerprint lock to prevent others from using it.
Nigerian example: A POS machine requires your PIN before allowing a withdrawal.
Illustration:
AUTHENTICATION PROCESS
+-------------------------------------------------+
| User enters username and password |
| โ |
| App checks password hash against stored hash |
| โ |
| If correct โ user is logged in (session created) |
| If incorrect โ error message |
+-------------------------------------------------+
Mini summary: User authentication ensures that only authorized users can access certain parts of your app. It is essential for security and personalization.
Definition: Password hashing converts a plain-text password into a fixed-length string of characters using a mathematical algorithm. It is a one-way process โ you cannot reverse it to get the original password.
Why it is important: Storing passwords in plain text is a huge security risk. If your database is breached, attackers would get all passwords. Hashing protects passwords so even if the database is stolen, attackers cannot easily get the actual passwords.
Simple explanation: Imagine you have a secret recipe. You don't write it down in plain text; you encode it in a way that only you can decode. Hashing is like encoding a password so it cannot be easily read.
How to hash in Flask:
from werkzeug.security import generate_password_hash, check_password_hash
# Hash a password
password_hash = generate_password_hash('mypassword')
# Check a password against the hash
is_correct = check_password_hash(password_hash, 'mypassword')
Real-life example: When you create an account on a website, your password is hashed before being stored in the database.
School example: Your teacher keeps your grades in a locked cabinet, not in plain sight.
Home example: You have a secret code for your diary that only you know.
Nigerian example: A banking app stores your PIN as a hash so that even if the database is hacked, the PIN is not exposed.
Illustration:
PASSWORD HASHING
+-------------------------------------------------+
| Plain password: "mysecret" |
| โ |
| generate_password_hash() |
| โ |
| Hashed: 'scrypt:32768:8:1$...' |
| (Stored in database) |
| โ |
| When user logs in: |
| check_password_hash(hashed, input) โ True/False|
+-------------------------------------------------+
Mini summary: Always hash passwords before storing
them. Use generate_password_hash() and
check_password_hash() from werkzeug.security.
Definition: Registration is the process of creating a new user account. Login is the process of verifying the user's credentials and starting a session.
Why it is important: These routes are the entry points for users to access your application. They are the foundation of user management.
Simple explanation: Think of registration as getting a library card (creating an account). Login is presenting that card to borrow a book (accessing your account).
Example routes:
from flask import render_template, request, redirect, url_for, flash
from werkzeug.security import generate_password_hash
from models import User, db
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
# Check if user already exists
existing_user = User.query.filter_by(username=username).first()
if existing_user:
flash('Username already taken.', 'danger')
return redirect(url_for('register'))
# Create new user
hashed_password = generate_password_hash(password)
new_user = User(username=username, email=email, password_hash=hashed_password)
db.session.add(new_user)
db.session.commit()
flash('Account created! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
if user and check_password_hash(user.password_hash, password):
# Log user in (we'll add session management later)
flash('Logged in successfully!', 'success')
return redirect(url_for('home'))
else:
flash('Invalid username or password.', 'danger')
return render_template('login.html')
Real-life example: A social media site has signup and login pages.
School example: You register for a club by filling out a form, then you log in to see club updates.
Home example: You create an account on a streaming service, then log in to watch movies.
Nigerian example: A fintech app has a signup page where you provide your BVN, email, and password, and a login page to access your dashboard.
Illustration:
REGISTRATION FLOW
+-------------------------------------------------+
| /register (GET) โ Show form |
| /register (POST) โ Validate, hash password, |
| create user, commit, flash |
| redirect to login |
+-------------------------------------------------+
| /login (GET) โ Show form |
| /login (POST) โ Check credentials, |
| if valid โ log in, redirect |
| else โ flash error |
+-------------------------------------------------+
Mini summary: Registration and login routes handle creating and authenticating users. Use hashing for passwords and flash messages for feedback.
Definition: Flask-Login is an extension that manages user sessions. It stores the user's ID in the session cookie and provides convenient methods to access the current user.
Why it is important: Without session management, you would have to manually check credentials on every request. Flask-Login automates this, making it easy to keep users logged in across pages.
Simple explanation: Think of a session as a temporary pass ๐ซ that your app gives to a user after they log in. The pass is valid for a certain time, and the app checks it on each page visit.
How to set up Flask-Login:
pip install flask-loginLoginManager.@login_required decorator to protected routes.login_user() and logout_user().Code example:
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login' # Redirect if not logged in
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/login', methods=['POST'])
def login():
# ... authenticate user ...
if user:
login_user(user)
flash('Logged in successfully.', 'success')
return redirect(url_for('dashboard'))
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('Logged out.', 'info')
return redirect(url_for('home'))
@app.route('/dashboard')
@login_required
def dashboard():
return f'Hello, {current_user.username}!'
Real-life example: After you log in to a website, you stay logged in as you navigate through pages until you log out or the session expires.
School example: Your school ID card lets you enter the building and stay in until you leave.
Home example: Your phone stays unlocked until you manually lock it or it times out.
Nigerian example: A banking app keeps you logged in for a period of time until you log out or the session expires.
Illustration:
FLASK-LOGIN FLOW
+-------------------------------------------------+
| 1. User logs in โ login_user(user) |
| 2. Flask-Login stores user ID in session |
| 3. On each request, load_user() gets the user |
| 4. @login_required protects routes |
| 5. Logout โ logout_user() clears session |
+-------------------------------------------------+
Mini summary: Flask-Login simplifies session management. It provides decorators to protect routes and functions to log users in and out.
Definition: Flash messages are one-time notifications that appear on the next page after an action (like registration or login). They are used to give feedback to the user.
Why it is important: Flash messages improve user experience by informing users about the result of their actions. They are also easy to implement in Flask.
Simple explanation: Imagine you submit a form, and a message pops up saying "Success!" or "Error: check your input." That is a flash message.
How to use:
from flask import flash
flash('Account created!', 'success')
flash('Invalid username or password.', 'danger')
# In template, use:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
Real-life example: After you reset your password, a message says "Password reset email sent."
School example: Your teacher writes "Well done!" on your test paper โ that is feedback.
Home example: A message on your phone says "Message sent successfully."
Nigerian example: After a successful transfer, your banking app shows "Transfer successful."
Illustration:
FLASH MESSAGE PROCESS
+-------------------------------------------------+
| Action (e.g., registration) โ flash('msg', 'category') |
| โ |
| Redirect to another page |
| โ |
| Next page displays the message (once) |
+-------------------------------------------------+
Mini summary: Flash messages are one-time notifications
for user feedback. Use flash() to set them and
get_flashed_messages() to display them in templates.
Definition: Flask-WTF integrates WTForms with Flask to provide form validation, CSRF protection, and easier form rendering.
Why it is important: Validating user input is crucial for security and data quality. Flask-WTF makes it easy to define form classes with built-in validators.
Simple explanation: Imagine you have a form that asks for an email address. Flask-WTF can check that the input actually looks like an email, and if not, it shows an error message.
How to use:
pip install flask-wtf
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo, Length
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=4, max=80)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=6)])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
Real-life example: A sign-up form that checks if the email is valid and if the password is strong enough.
School example: A registration form for a club that ensures all required fields are filled.
Home example: A feedback form that validates your email address before submitting.
Nigerian example: A banking app's registration form validates that your BVN has 11 digits.
Illustration:
WTFORM VALIDATION
+-------------------------------------------------+
| Form class with validators |
| โ |
| In route: |
| form = RegistrationForm() |
| if form.validate_on_submit(): |
| # process data |
| else: |
| # show errors in template |
+-------------------------------------------------+
Mini summary: Flask-WTF provides form classes with built-in validators. It simplifies input validation and adds CSRF protection.
Now we will build a complete Flask application with database and user authentication, using all the concepts we have learned.
Scenario: A simple "User Dashboard" app where users can register, log in, and view a personalized dashboard.
Project Structure:
my_auth_app/
โโโ app.py
โโโ models.py
โโโ forms.py
โโโ templates/
โ โโโ base.html
โ โโโ home.html
โ โโโ register.html
โ โโโ login.html
โ โโโ dashboard.html
โโโ static/
โ โโโ style.css
โโโ venv/
โโโ requirements.txt
Code (app.py):
from flask import Flask, render_template, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from models import db, User
from forms import RegistrationForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/')
def home():
return render_template('home.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data)
user = User(username=form.username.data, email=form.email.data, password_hash=hashed_password)
db.session.add(user)
db.session.commit()
flash('Your account has been created! You can now log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and check_password_hash(user.password_hash, form.password.data):
login_user(user, remember=form.remember.data)
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Login unsuccessful. Please check email and password.', 'danger')
return render_template('login.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out.', 'info')
return redirect(url_for('home'))
@app.route('/dashboard')
@login_required
def dashboard():
return render_template('dashboard.html')
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
models.py:
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
db = SQLAlchemy()
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
def __repr__(self):
return f'<User {self.username}>'
forms.py:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Email, Length, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=4, max=80)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=6)])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
Templates: (omitted for brevity, but would include
base.html with flash messages, and forms with form.hidden_tag()
and {{ form.field() }})
What we used:
Illustration:
COMPLETE APP FLOW
+-------------------------------------------------+
| Home โ / โ public page |
| Register โ /register โ create user |
| Login โ /login โ authenticate, start session |
| Dashboard โ /dashboard โ protected (requires login) |
| Logout โ /logout โ end session |
+-------------------------------------------------+
Mini summary: The complete app combines Flask-SQLAlchemy, Flask-Login, Werkzeug, and Flask-WTF to create a secure, user-friendly web application with authentication.
Definition: When deploying a Flask app with a database, you need to ensure the database is properly set up on the server and the connection string is correctly configured.
Why it is important: Your local SQLite file won't be available on the server. You need to either use a hosted database or upload the SQLite file and update the URI.
Simple explanation: It's like moving your notebook from your desk to the library. You need to make sure the notebook (database) is in the right place and the librarian (your app) knows where to find it.
Steps for PythonAnywhere:
SQLALCHEMY_DATABASE_URI to point to the server path.db.create_all() (or use a script).SECRET_KEY as an environment variable.Real-life example: A company moves its application from a development server to a production server.
School example: You submit your project to the teacher (deployment) and they run it on their computer.
Home example: You take a photo from your phone and send it to your computer.
Nigerian example: A fintech startup deploys its app to AWS and configures a PostgreSQL database.
Illustration:
DEPLOYMENT WITH DATABASE
+-------------------------------------------------+
| Local: SQLite file on your computer |
| โ |
| Upload files to server |
| โ |
| Server: Update URI path |
| โ |
| Run db.create_all() in the server's Python |
| Set environment variables for SECRET_KEY |
| App goes live! |
+-------------------------------------------------+
Mini summary: When deploying, ensure the database URI is correct and the database exists. Use environment variables for sensitive settings.
| Word | Simple Definition |
|---|---|
| Database | A structured collection of data stored permanently. |
| ORM (Object-Relational Mapper) | A tool that maps Python objects to database tables. |
| SQLAlchemy | A Python library providing ORM for databases. |
| Model | A Python class that represents a database table. |
| CRUD | Create, Read, Update, Delete โ the four basic operations. |
| Authentication | The process of verifying a user's identity. |
| Password Hashing | Converting a password into a secure, irreversible string. |
| Session | A temporary storage for user data between requests. |
| Flask-Login | An extension that manages user sessions in Flask. |
| Flash Message | A one-time notification for user feedback. |
| Form Validation | Checking user input for correctness and security. |
| CSRF | Cross-Site Request Forgery โ a security attack prevented by tokens. |
@login_required.
pip install flask-sqlalchemy.SQLAlchemy and initialize it with your app.db.Model.db.create_all() inside the app context.pip install flask-login.LoginManager.@login_required to protected routes.login_user() and logout_user().generate_password_hash() and verify with check_password_hash().pip install flask-wtf.FlaskForm.validate_on_submit().form.hidden_tag() and form.field().db.Model.
db.session.add(), db.session.commit(),
and db.session.delete().
generate_password_hash() and
check_password_hash().
login_user(), logout_user(), and
@login_required.
flash() and get_flashed_messages().
| Mistake | How to Avoid It |
|---|---|
Forgetting to import db in models and forms |
Always import db from the module where it is
defined. |
Not calling db.create_all() before running |
Run db.create_all() once to create tables. |
| Storing plain-text passwords | Always hash passwords with werkzeug.security. |
Forgetting to set the login_view on
LoginManager |
Set login_manager.login_view = 'login' to
redirect unauthenticated users. |
Not using form.hidden_tag() in templates |
Always include form.hidden_tag() for CSRF
protection. |
| Not validating input before saving to database | Always use Flask-WTF validators or manual checks. |
| Hardcoding secret key | Use environment variables for SECRET_KEY in
production. |
| Forgetting to commit after changes | Always call db.session.commit() after
modifications. |
@login_required to protect routes
that require authentication.
first()
instead of all() when you only need one record.
TABLE: users
+-------------------------------------------------+
| id | INTEGER PRIMARY KEY AUTOINCREMENT |
| username| VARCHAR(80) NOT NULL UNIQUE |
| email | VARCHAR(120) NOT NULL UNIQUE |
| password| VARCHAR(128) NOT NULL |
+-------------------------------------------------+
ORM MAPPING
+-------------------------------------------------+
| Python Class โ SQLAlchemy โ Table |
| User ORM users |
| (id, name) (id, name) |
+-------------------------------------------------+
AUTHENTICATION FLOW
+-------------------------------------------------+
| 1. User submits login form (POST /login) |
| 2. App queries database for user by email |
| 3. If user exists, check password hash |
| 4. If correct, create session (login_user) |
| 5. Redirect to dashboard |
| 6. On subsequent requests, load_user() checks |
| session and retrieves user object |
| 7. @login_required protects routes |
| 8. Logout destroys session (logout_user) |
+-------------------------------------------------+
FLASH MESSAGE CYCLE
+-------------------------------------------------+
| Route: flash('msg', 'category') |
| โ |
| Redirect to another page |
| โ |
| Template: get_flashed_messages() displays msg |
| โ |
| Message removed from session (shown only once) |
+-------------------------------------------------+
| Feature | SQLite | PostgreSQL |
|---|---|---|
| Serverless | Yes | No (client-server) |
| Setup complexity | Very simple (built-in) | More complex |
| Data size | Small to medium | Large |
| Concurrency | Limited (one writer) | High |
| Use case | Development, small apps | Production, large apps |
| Algorithm | Security | Speed | Usage |
|---|---|---|---|
| MD5 | Weak (cracked) | Fast | Not recommended |
| SHA-1 | Weak (collisions) | Fast | Not recommended |
| bcrypt | Strong | Slow | Recommended |
| scrypt | Strong | Slow | Recommended |
| PBKDF2 | Strong | Moderate | Used by werkzeug |
Lesson 1 Summary: Databases store data permanently; apps need them to remember information.
Lesson 2 Summary: SQLAlchemy ORM maps Python classes to database tables, making database code simpler.
Lesson 3 Summary: Flask-SQLAlchemy integrates SQLAlchemy into Flask. Configure the URI and create tables.
Lesson 4 Summary: Models are Python classes that define table structures. Use column types to specify data.
Lesson 5 Summary: CRUD operations are Create, Read, Update, Delete. Use db.session methods.
Lesson 6 Summary: User authentication verifies identity and protects sensitive areas.
Lesson 7 Summary: Password hashing secures passwords. Use werkzeug.security utilities.
Lesson 8 Summary: Registration and login routes handle account creation and authentication.
Lesson 9 Summary: Flask-Login manages sessions with login_user(), logout_user(), and @login_required.
Lesson 10 Summary: Flash messages give one-time feedback to users.
Lesson 11 Summary: Flask-WTF provides forms with validation and CSRF protection.
Lesson 12 Summary: Combining all components creates a secure, functional authentication app.
Lesson 13 Summary: Deployment requires updating the database URI and using environment variables.
Congratulations! You have completed Module Two of Python Fundamentals Level Two ๐. You have added two essential features to your Flask toolkit: databases and user authentication.
You learned how to use Flask-SQLAlchemy to define
models and perform CRUD operations. You now understand the importance of
password hashing and how to implement it securely with
werkzeug.security. You set up Flask-Login
to manage user sessions and protect routes. You also added
flash messages and form validation
with Flask-WTF.
You built a complete authentication app that allows users to register, log in, and access a personalized dashboard. This is the foundation of almost every web application you will ever build.
In the next module, you will learn how to extend your application with more advanced features like email confirmation, password reset, and user roles. You will also learn how to use Flask-Migrate for database schema changes.
Keep practicing by adding new features to your app. The skills you have learned here are in high demand and will serve you well in your programming career. Well done! ๐๐
current_user.is_authenticated in API routes.
User model and run a
migration (or recreate the table if in development).
db.create_all()?
db.session.commit()?werkzeug.security.
@login_required protects routes from unauthenticated users. (True / False)db.session.commit() saves changes to the database. (True / False)db.create_all() drops existing tables and recreates them. (True / False)hash_password()
generate_password_hash()
encrypt_password()
secure_password()
@login_protected
@auth_required
@login_required
@secure_route
login()
log_in_user()
login_user()
user_login()
db.session.commit()?
db.session.remove()
db.session.delete()
db.session.destroy()
db.session.clear()
db.Integer
db.String
db.Text
db.Boolean
db.Password is not a standard column type.)
db.create_all()?
@login_required do?
Match the term on the left with its description on the right:
| Term | Description |
|---|---|
| 1. SQLAlchemy | A. Manages user sessions |
| 2. Flask-Login | B. ORM for Python |
| 3. Flask-WTF | C. Password hashing |
| 4. werkzeug.security | D. Form validation |
| 5. Flash message | E. One-time notification |
| 6. CRUD | F. Create, Read, Update, Delete |
Answers: 1-B, 2-A, 3-D, 4-C, 5-E, 6-F
db.session.add() and db.session.commit()?@login_required and how does it work?Scenario 1:
Ada wants to add a "Remember Me" checkbox to her login form so that
users stay logged in for a longer period. How would she modify her login
route and form to implement this? (Hint: use Flask-Login's
remember parameter.)
Scenario 2:
Chidi has a Post model with fields id,
title, content, user_id. He wants
to display all posts by the currently logged-in user on their dashboard.
Write the SQLAlchemy query to fetch these posts.
Scenario 3:
Zainab wants to add a profile page where users can update their email and password. She wants to use a form with validation. Write the route and form code for this feature.
Activity Title: Build a Simple Blog with User Accounts
Instructions:
Activity Title: Build a Personal Diary App
Instructions:
Entry model (id, title,
content, created_at, user_id).
Project Title: Build a User Management System
Description:
Create a Flask application that manages users with roles (admin and regular). The app should:
This project will test your ability to handle different user roles and permissions.
Assignment Title: Build a Product Review System
Instructions:
Challenge Title: Build a RESTful API with Flask and JWT Authentication
Build a RESTful API using Flask that provides endpoints for user registration, login, and a protected resource. Use JWT (JSON Web Tokens) for authentication instead of Flask-Login. The API should:
pyjwt library to generate and verify tokens.This challenge will test your ability to build an API and use token-based authentication, which is widely used in modern web applications.
Fill-in-the-Blank Answers:
generate_password_hash@login_requireddb.session.commit()login_user()logout_user()True or False Answers:
Multiple Choice Answers:
werkzeug.security.
login_user(), logout_user(), and
@login_required.
Congratulations on completing Module Two of Level Two! ๐ You have added databases and authentication to your Flask toolkit. In the next module, you will learn:
To prepare, review the concepts from this module and practice building authentication systems. The more you practice, the easier it will be to add new features.
Keep coding, keep exploring, and never stop learning. See you in the next module! ๐๐
๐ End of Module Two โ Python Fundamentals Level Two ๐