0
0
Flaskframework~3 mins

Why G object for request-scoped data in Flask? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to keep your code clean by sharing data effortlessly during each web request!

The Scenario

Imagine building a web app where you need to share user info across different parts of your code during a single web request.

You try passing the user data manually through every function call.

The Problem

Passing data manually is tiring and error-prone.

You might forget to pass it somewhere, causing bugs.

It also clutters your code with extra parameters everywhere.

The Solution

The Flask g object lets you store data just for the current request.

You can set user info once and access it anywhere during that request without passing it around.

Before vs After
Before
def view(user):
    return do_something(user)

def do_something(user):
    return f"Hello, {user}!"
After
from flask import g

def view():
    g.user = 'Alice'
    return do_something()

def do_something():
    return f"Hello, {g.user}!"
What It Enables

You can easily share data across your app during a request without messy function parameters.

Real Life Example

When a user logs in, you store their info in g.user once, then any part of your app can check who is logged in during that request.

Key Takeaways

G object stores data only for the current request.

It avoids passing data manually through many functions.

Makes your code cleaner and less error-prone.