We create a user model with a password to safely store user login details. This helps keep user accounts secure.
When building a website that requires users to sign up and log in.
When you want to protect user passwords by not saving them as plain text.
When you need to check if a user's password is correct during login.
When managing user accounts in a Flask web application.
Syntax
Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
The password is never saved directly. Instead, a hashed version is stored.
Use set_password to save a password and check_password to verify it.
Examples
Create a new user and save a hashed password to the database.
Flask
user = User(username='alice')
user.set_password('mypassword123')
db.session.add(user)
db.session.commit()
Check if the entered password matches the stored hashed password.
Flask
user = User.query.filter_by(username='alice').first()
if user and user.check_password('mypassword123'):
print('Login successful')
else:
print('Login failed')
Sample Program
This Flask app creates a user model, saves a hashed password, and checks it. It uses an in-memory database for simplicity.
Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
with app.app_context():
db.create_all()
# Create user
user = User(username='bob')
user.set_password('secret123')
db.session.add(user)
db.session.commit()
# Verify password
user_check = User.query.filter_by(username='bob').first()
if user_check and user_check.check_password('secret123'):
print('Password is correct')
else:
print('Password is incorrect')
OutputSuccess
Important Notes
Never store passwords as plain text to keep user data safe.
Use werkzeug.security functions to hash and check passwords easily.
Always test password checking to avoid login errors.
Summary
User models store usernames and hashed passwords.
Use set_password to hash and save passwords.
Use check_password to verify passwords during login.
Practice
(1/5)
1. What is the main purpose of the set_password method in a Flask user model?
easy
A. To delete the user's password from the database
B. To hash and store the user's password securely
C. To check if the password entered matches the stored password
D. To display the user's password in plain text
Solution
Step 1: Understand the role of set_password
This method is used to convert a plain password into a secure hashed version before saving it.
Step 2: Differentiate from check_password
check_password is for verifying passwords, not setting them.
Final Answer:
To hash and store the user's password securely -> Option B
A. The order of arguments in check_password_hash is reversed
B. password_hash should be initialized as an empty string, not None
C. set_password should return the hashed password
D. The class is missing a username attribute
Solution
Step 1: Review check_password_hash usage
The correct order is check_password_hash(stored_hash, password).
Step 2: Identify argument mistake
The code passes password first and self.password_hash second, which is wrong.
Final Answer:
The order of arguments in check_password_hash is reversed -> Option A
Quick Check:
check_password_hash needs (hash, password) order [OK]
Hint: check_password_hash(hash, password) order matters [OK]
Common Mistakes:
Swapping arguments in check_password_hash
Initializing password_hash as None causes no error but is not best
Expecting set_password to return a value
Confusing missing attributes with password errors
5. You want to add a method change_password to your Flask user model that updates the password only if the old password matches. Which implementation correctly applies this logic?
hard
A. def change_password(self, old_password, new_password):
if self.check_password(old_password):
self.set_password(new_password)
return True
return False
B. def change_password(self, old_password, new_password):
self.set_password(new_password)
return True
C. def change_password(self, old_password, new_password):
if old_password == new_password:
self.set_password(new_password)
return True
return False
D. def change_password(self, old_password, new_password):
if not self.check_password(new_password):
self.set_password(old_password)
return True
return False
Solution
Step 1: Verify old password before changing
The method must check if the old password matches using check_password.
Step 2: Update password only if old password is correct
If the check passes, call set_password with the new password and return True; else return False.
Final Answer:
def change_password(self, old_password, new_password):
if self.check_password(old_password):
self.set_password(new_password)
return True
return False -> Option A
Quick Check:
Change password only if old password matches [OK]
Hint: Always verify old password before setting new one [OK]
Common Mistakes:
Changing password without verifying old password
Comparing old and new passwords incorrectly
Swapping old and new passwords in checks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.