0
0
Flaskframework~3 mins

Why Before_request hooks in Flask? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a login check once and have it work everywhere automatically?

The Scenario

Imagine you have a web app where every page needs to check if a user is logged in before showing content.

You write this check on every single page route manually.

The Problem

Manually adding login checks to every route is repetitive and easy to forget.

This leads to security holes or inconsistent behavior across pages.

The Solution

Before_request hooks let you run code automatically before every request.

This means you write your login check once, and it applies everywhere.

Before vs After
Before
def page():
    if not logged_in():
        return redirect('/login')
    return 'Page content'
After
@app.before_request
def check_login():
    if not logged_in():
        return redirect('/login')
What It Enables

You can centralize common checks or setup steps, making your app safer and easier to maintain.

Real Life Example

Many websites require users to be logged in to access their dashboard.

Using before_request hooks, the login check runs automatically before showing any dashboard page.

Key Takeaways

Manually repeating code for every route is error-prone.

Before_request hooks run code before all requests automatically.

This keeps your app consistent, secure, and easier to update.