Building a Login and Registration Application with Flask: A Step-by-Step Guide

Flask is a lightweight web framework for Python, offering simplicity and flexibility. It’s known for its minimalistic design and ease of use, making it ideal for building web applications and APIs swiftly. With its modular structure and extensive documentation, Flask empowers developers to create scalable and maintainable projects. Its powerful extensions ecosystem further enhances its capabilities, enabling integration with various technologies and services. Whether it’s a small project or a large-scale application, Flask provides the tools needed to get started quickly and efficiently.

Getting Started

Today, in this article, we’ll explore the process of implementing basic Flask login authentication. Before diving in, let’s confirm that we’ve installed all the essential packages within our project directory’s virtual environment. Assuming you’re familiar with setting up a project directory and virtual environment, let’s proceed with installing the required packages.

$ pip install flask
$ pip install Flask-SQLAlchemy

Now that Flask and Flask-SQLAlchemy are installed, it’s time to dive into coding. Let’s begin by creating our Flask app file, “app.py”, right in the project directory.

Flask Application File:

In our app.py, let’s begin by importing the necessary modules and libraries for our application. This includes Flask for web development, SQLAlchemy for database management, and secrets for generating a secret key.

from flask import Flask, url_for, render_template, request, redirect, session
from flask_sqlalchemy import SQLAlchemy
import secrets

After importing the required libraries, let’s initialize the Flask application, generate and set a secret key for session security, and configure the database URI to use SQLite.

app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

The following code outlines the structure of the User model in the database, specifying the columns for user ID, username, and password.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))

    def __init__(self, username, password):
        self.username = username
        self.password = password

Great! We’ve successfully created our User database model. Now, let’s set up our first route to handle requests to the root URL (“/”). If the user is logged in (determined by the session), it will render the home page template; otherwise, it will render the login page template.

@app.route('/', methods=['GET'])
def index():
    if session.get('logged_in'):
        return render_template('home.html')
    else:
        return render_template('login.html')

The following route is responsible for user registration. When the request method is POST, it attempts to add a new user to the database and redirects to the login page upon successful registration. If the username already exists, an error message is displayed. If the method is GET, it renders the registration form.

@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        try:
            db.session.add(User(username=request.form['username'], password=request.form['password']))
            db.session.commit()
            return redirect(url_for('login'))
        except:
            return render_template('register.html', message="User Already Exists")
    else:
        return render_template('register.html')

Now, let’s establish a route to manage user login. If the request method is GET, it renders the login form. If the method is POST, it verifies the provided username and password against the database. If the credentials are accurate, it sets the session as logged in and redirects to the home page; otherwise, it displays an error message.

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        u = request.form['username']
        p = request.form['password']
        data = User.query.filter_by(username=u, password=p).first()
        if data is not None:
            session['logged_in'] = True
            return redirect(url_for('index'))
        return render_template('login.html', message="Incorrect Details")

Our final Flask app route manages user logout. It effectively sets the session as logged out and redirects to the index page.

@app.route('/logout', methods=['GET', 'POST'])
def logout():
    session['logged_in'] = False
    return redirect(url_for('index'))

Let’s incorporate a block to ensure that the application runs only if executed as the main script. This block will create all necessary database tables and run the Flask application.

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run()

At last, let’s consolidate all the code blocks into a single file named ‘app.py’, bringing together our entire application logic.

from flask import Flask, url_for, render_template, request, redirect, session
from flask_sqlalchemy import SQLAlchemy
import secrets
secrets
secrets

app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))

    def __init__(self, username, password):
        self.username = username
        self.password = password


@app.route('/', methods=['GET'])
def index():
    if session.get('logged_in'):
        return render_template('home.html')
    else:
        return render_template('login.html')


@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        try:
            db.session.add(User(username=request.form['username'], password=request.form['password']))
            db.session.commit()
            return redirect(url_for('login'))
        except:
            return render_template('login.html', message="User Already Exists")
    else:
        return render_template('register.html')


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        u = request.form['username']
        p = request.form['password']
        data = User.query.filter_by(username=u, password=p).first()
        if data is not None:
            session['logged_in'] = True
            return redirect(url_for('index'))
        return render_template('login.html', message="Incorrect Details")


@app.route('/logout', methods=['GET', 'POST'])
def logout():
    session['logged_in'] = False
    return redirect(url_for('index'))
    

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run()

In conclusion, the provided code sets up a basic Flask web application with user authentication functionality. Here’s a summary:

  • Imports and Setup: The necessary Flask modules are imported, along with SQLAlchemy for database management and the secrets module for generating a secret key.
  • Flask Application Setup: An instance of the Flask application is created, and a secret key is generated to secure the session. The SQLite database URI is configured, and SQLAlchemy is initialized with the Flask application.
  • Database Model: A User class is defined as a SQLAlchemy model, representing users in the database. It contains fields for id, username, and password.
  • Routes and Views: Several routes are defined for different pages:
    • /: Renders the home page or the login page based on whether the user is logged in.
    • /register/: Handles user registration via a form submission.
    • /login/: Manages user login authentication.
    • /logout: Logs the user out by clearing the session.
  • Main Section: Checks if the script is being run directly, creates the necessary database tables, and starts the Flask application.

Overall, this code provides a foundation for building a simple web application with user authentication features using Flask and SQLAlchemy.


Leave a Reply

Your email address will not be published. Required fields are marked *

DarkLight
×