Welcome to this comprehensive guide on creating a User Model and Loader using Flask! This tutorial is designed to be friendly and approachable, so let's get started.
A User Model is a representation of a user in a database. It's crucial for managing user data, such as username, email, password, and other personal details.
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(128))
def __repr__(self):
return f"<User {self.username}>"š” Pro Tip: Flask provides flask_sqlalchemy for easy database integration.
The User Loader is responsible for fetching user data from the database by their ID.
from werkzeug.security import check_password_hash, generate_password_hash
def get_user_by_id(user_id):
user = User.query.get(user_id)
return user
def set_password(user, password):
user.password = generate_password_hash(password)
def check_password(user, password):
return check_password_hash(user.password, password)š Note: Always hash the password before storing it in the database for security reasons.
Let's create a simple registration and login function using our User Model and Loader.
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
user = User(username=username, email=email, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
user = get_user_by_id(1) # In a real app, fetch user by email
if check_password(user, password):
# If login successful, do something like redirect to user's dashboard
return redirect(url_for('dashboard'))
# If login fails, show an error message
return render_template('login.html', error="Invalid credentials.")
return render_template('login.html')What is the purpose of the User Model in Flask?
That's it for this lesson! In the next tutorial, we'll delve deeper into Flask, exploring topics like User Authentication and Authorization. Happy coding! šš»