Welcome to our comprehensive guide on implementing user login functionality using Flask, a powerful web framework for Python! In this tutorial, we'll walk you through building a login system step-by-step. By the end, you'll have a solid understanding of how to secure user authentication in your web applications.
šÆ Objective: Learn how to create a user login system using Flask.
User login is a crucial feature in web applications that enables users to access their personal account and protected resources. In this tutorial, we'll create a simple login system where users can register, log in, and access protected pages.
Before we dive into the login system, let's set up a new Flask project:
$ mkdir my-flask-app
$ cd my-flask-app
$ pip install flask flask-sqlalchemyCreate a new file named app.py and let's get started!
We'll use Flask-SQLAlchemy to manage our database. First, import the necessary modules and initialize the SQLAlchemy extension:
from flask import Flask, render_template, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)Now, let's create the User model:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
def __repr__(self):
return f'<User {self.username}>'Initialize the database:
if __name__ == '__main__':
db.create_all()
app.run(debug=True)Let's create a registration form and handle user registration in a separate route. First, create the registration template:
<!-- templates/register.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<h1>Register</h1>
<form method="POST" action="{{ url_for('register') }}">
<!-- ... -->
</form>
</body>
</html>Now, create the register route in app.py and implement user registration logic:
@app.route('/register', methods=['GET', 'POST'])
def register():
# ...
if form.validate_on_submit():
user = User(username=form.username.data, password=form.password.data)
db.session.add(user)
db.session.commit()
flash('Account created! You can now log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)Next, we'll create a login form and handle user authentication:
<!-- templates/login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<h1>Login</h1>
<form method="POST" action="{{ url_for('login') }}">
<!-- ... -->
</form>
</body>
</html>Create the login route in app.py and implement user authentication logic:
@app.route('/login', methods=['GET', 'POST'])
def login():
# ...
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user and user.password == form.password.data:
# Login successful
return redirect(url_for('protected'))
else:
# Invalid credentials
flash('Invalid username or password', 'danger')
return render_template('login.html', form=form)Now that we have a login system, let's protect some routes with authentication:
@app.route('/protected')
@login_required
def protected():
# ...
return 'Protected content.'
@app.route('/logout')
def logout():
# ...
return redirect(url_for('login'))
def login_required(view):
@wraps(view)
def wrapped_view(*args, **kwargs):
if 'username' not in session:
return redirect(url_for('login'))
return view(*args, **kwargs)
return wrapped_viewš Note: We've created a login_required decorator to protect routes easily.
Now, you can test your login system by running the application and navigating to the registration and login pages.
Which Flask extension is used to manage our database?
Congratulations! You've built a simple but functional user login system using Flask. You've learned about creating a database, registering users, implementing login functionality, and protecting routes. With this knowledge, you can now create more secure web applications!
š” Pro Tip: Remember to secure your application by hashing passwords and using secure cookies for session management.
That's all for this tutorial. Happy coding! š
š Important: This tutorial is just a starting point for building user login systems using Flask. There's much more to learn about web security and best practices for user authentication. Keep exploring and learning! š±