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.
Practice
g object in Flask?Solution
Step 1: Understand the scope of
Theggobject is designed to hold data only during the life of one request.Step 2: Compare with other storage options
Unlike session or global variables,gdoes not persist data beyond the current request.Final Answer:
To store data temporarily during a single request -> Option AQuick Check:
g= request-scoped storage [OK]
g lasts only for one request [OK]- Thinking
gstores data across requests - Confusing
gwith session or global variables - Assuming
gmanages database connections automatically
g object inside a Flask view function?Solution
Step 1: Recall how to assign attributes in
ggacts like a simple object where you assign attributes using dot notation.Step 2: Check each option's syntax
g.user = 'Alice' usesg.user = 'Alice', which is the correct way. g['user'] = Alice uses dictionary style which is invalid. Options B and C use methods thatgdoes not have.Final Answer:
g.user = 'Alice' -> Option AQuick Check:
Use dot notation to setgattributes [OK]
g.attribute = value [OK]- Using dictionary syntax like
g['key'] - Trying to call non-existent methods on
g - Confusing
gwith Flask's session object
from flask import Flask, g
app = Flask(__name__)
@app.before_request
def before():
g.value = 10
@app.route('/')
def index():
g.value += 5
return str(g.value)What will be the output when you visit the '/' route?
Solution
Step 1: Understand the
Before each request,before_requestfunctiong.valueis set to 10.Step 2: Analyze the
It adds 5 toindexfunctiong.value, making it 15, then returns it as a string.Final Answer:
15 -> Option CQuick Check:
g.valuestarts 10, adds 5 = 15 [OK]
g resets each request; additions apply after setup [OK]- Assuming
g.valuekeeps old values between requests - Forgetting
before_requestruns before route - Expecting an error due to missing attribute
g? from flask import Flask, g
app = Flask(__name__)
@app.route('/')
def index():
if not hasattr(g, 'counter'):
g.counter = 0
g.counter += 1
return str(g.counter)Solution
Step 1: Understand
gscopegis reset for each request, socounterdoes not persist between requests.Step 2: Analyze the counter behavior
Each request starts fresh, socounteris set to 0 then incremented to 1 every time.Final Answer:
The counter resets on every request, so it always returns 1 -> Option DQuick Check:
gdata is request-scoped, no persistence [OK]
g resets each request; no data persists [OK]- Expecting
g.counterto keep increasing across requests - Thinking
gforbids new attributes - Confusing
gwith session or global variables
g. Which code snippet correctly opens the connection once per request and reuses it in multiple functions?from flask import Flask, g
app = Flask(__name__)
def get_db():
if not hasattr(g, 'db'):
g.db = open_database_connection()
return g.db
@app.route('/')
def index():
db = get_db()
# use db
return 'OK'What is the main benefit of this pattern?
Solution
Step 1: Analyze the
It checks ifget_dbfunctiong.dbexists; if not, it opens the connection and saves it tog.Step 2: Understand request scope of
The connection is stored only for the current request, so multiple calls reuse the same connection.gStep 3: Compare options
It shares one connection per request, avoiding multiple opens correctly describes this behavior. It opens a new database connection on every function call is wrong because it avoids multiple opens. It stores the connection globally for all requests is wrong becausegis not global. It closes the connection automatically after each function is incorrect; closing is not automatic here.Final Answer:
It shares one connection per request, avoiding multiple opens -> Option BQuick Check:
Usegto cache per-request resources [OK]
g to reuse during request [OK]- Thinking
gstores data globally across requests - Opening new connections on every function call
- Assuming
gauto-closes resources
Ready to prove it?
Pass the test and this pattern moves unknown
