Discover how to keep your code clean by sharing data effortlessly during each web request!
Why G object for request-scoped data in Flask? - Purpose & Use Cases
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.
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 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.
def view(user): return do_something(user) def do_something(user): return f"Hello, {user}!"
from flask import g def view(): g.user = 'Alice' return do_something() def do_something(): return f"Hello, {g.user}!"
You can easily share data across your app during a request without messy function parameters.
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.
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.