The g object is used to store data during a single request. It helps share information between functions without using global variables.
Click to reveal answer
beginner
How long does data stored in g last?
Data in g lasts only for the current request. It is cleared automatically after the request ends.
Click to reveal answer
beginner
How do you store a value in the g object?
You assign a value like this: g.my_value = 42. This value can then be accessed anywhere during the request.
Click to reveal answer
intermediate
Why is g preferred over global variables for request data?
Because g is unique to each request, it avoids conflicts and data leaks between users or requests, unlike global variables.
Click to reveal answer
intermediate
Can you give an example use case for the g object?
A common use is to store a database connection during a request so multiple functions can use it without reopening connections.
Click to reveal answer
What does the Flask g object store?
AData for the current request only
BGlobal data shared across all requests
CUser session data stored permanently
DConfiguration settings for the app
✗ Incorrect
The g object stores data only for the current request, not globally or permanently.
How do you access the g object in Flask?
AUse <code>request.g</code>
BImport it from flask and use it directly
CUse <code>session.g</code>
DIt is a global variable without import
✗ Incorrect
You import g from Flask with from flask import g and then use it.
What happens to data stored in g after the request ends?
AIt is saved to a file
BIt is sent to the client
CIt persists for the next request
DIt is cleared automatically
✗ Incorrect
Data in g is cleared automatically after the request finishes.
Which of these is a good use for g?
AStoring app configuration
BSaving user login info permanently
CStoring a database connection for the request
DKeeping global counters
✗ Incorrect
g is ideal for request-specific data like a database connection.
Why avoid using global variables instead of g for request data?
AGlobal variables can cause data conflicts between requests
BGlobal variables are faster
CGlobal variables are cleared after each request
DGlobal variables are only for configuration
✗ Incorrect
Global variables can mix data between requests, causing bugs. g keeps data separate per request.
Explain what the Flask g object is and why it is useful.
Think about how to share info safely during one web request.
You got /4 concepts.
Describe a practical example of using the g object in a Flask app.
Consider resources that need to be reused during one request.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of the g object in Flask?
easy
A. To store data temporarily during a single request
B. To store data permanently across all requests
C. To manage database connections globally
D. To handle user sessions across multiple requests
Solution
Step 1: Understand the scope of g
The g object is designed to hold data only during the life of one request.
Step 2: Compare with other storage options
Unlike session or global variables, g does not persist data beyond the current request.
Final Answer:
To store data temporarily during a single request -> Option A
Quick Check:
g = request-scoped storage [OK]
Hint: Remember: g lasts only for one request [OK]
Common Mistakes:
Thinking g stores data across requests
Confusing g with session or global variables
Assuming g manages database connections automatically
2. Which of the following is the correct way to store a value in the g object inside a Flask view function?
easy
A. g.user = 'Alice'
B. g.add('user', 'Alice')
C. g.set('user', 'Alice')
D. g['user'] = Alice
Solution
Step 1: Recall how to assign attributes in g
g acts like a simple object where you assign attributes using dot notation.
Step 2: Check each option's syntax
g.user = 'Alice' uses g.user = 'Alice', which is the correct way. g['user'] = Alice uses dictionary style which is invalid. Options B and C use methods that g does not have.
What will be the output when you visit the '/' route?
medium
A. 10
B. 5
C. 15
D. Error: AttributeError
Solution
Step 1: Understand the before_request function
Before each request, g.value is set to 10.
Step 2: Analyze the index function
It adds 5 to g.value, making it 15, then returns it as a string.
Final Answer:
15 -> Option C
Quick Check:
g.value starts 10, adds 5 = 15 [OK]
Hint: Remember g resets each request; additions apply after setup [OK]
Common Mistakes:
Assuming g.value keeps old values between requests
Forgetting before_request runs before route
Expecting an error due to missing attribute
4. What is wrong with this Flask code using 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)
medium
A. It will raise an error because g cannot have new attributes
B. The code will cause a syntax error due to missing import
C. The counter will increase across requests, causing unexpected results
D. The counter resets on every request, so it always returns 1
Solution
Step 1: Understand g scope
g is reset for each request, so counter does not persist between requests.
Step 2: Analyze the counter behavior
Each request starts fresh, so counter is set to 0 then incremented to 1 every time.
Final Answer:
The counter resets on every request, so it always returns 1 -> Option D
Quick Check:
g data is request-scoped, no persistence [OK]
Hint: Remember g resets each request; no data persists [OK]
Common Mistakes:
Expecting g.counter to keep increasing across requests
Thinking g forbids new attributes
Confusing g with session or global variables
5. You want to share a database connection during a single Flask request using 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?
hard
A. It opens a new database connection on every function call
B. It shares one connection per request, avoiding multiple opens
C. It stores the connection globally for all requests
D. It closes the connection automatically after each function
Solution
Step 1: Analyze the get_db function
It checks if g.db exists; if not, it opens the connection and saves it to g.
Step 2: Understand request scope of g
The connection is stored only for the current request, so multiple calls reuse the same connection.
Step 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 because g is 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 B
Quick Check:
Use g to cache per-request resources [OK]
Hint: Cache resources in g to reuse during request [OK]
Common Mistakes:
Thinking g stores data globally across requests
Opening new connections on every function call
Assuming g auto-closes resources
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.