Bird
Raised Fist0
Flaskframework~10 mins

G object for request-scoped data in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - G object for request-scoped data
Start Request
↓
Create g object
↓
Store data in g
↓
Use g data in view
↓
Request ends
↓
g data cleared
Each web request creates a fresh g object to store data accessible only during that request.
Execution Sample
Flask
from flask import Flask, g, request
app = Flask(__name__)

@app.before_request
def before():
    g.user = request.headers.get('User')

@app.route('/')
def index():
    return f"Hello, {g.user}!"
This code saves the user from request headers into g before handling the request, then uses it in the response.
Execution Table
StepActiong.user valueOutput
1Start request, create gunsetNo output yet
2before_request runs, sets g.user = 'Alice''Alice'No output yet
3index() reads g.user'Alice'Returns 'Hello, Alice!'
4Request ends, g clearedunsetNo output
💡 Request ends, g object data is cleared and not shared between requests
Variable Tracker
VariableStartAfter Step 2After Step 3Final
g.userunset'Alice''Alice'unset (cleared after request)
Key Moments - 2 Insights
Why does g.user reset to None after the request ends?
Because g is request-scoped, it only lives during one request. After the request finishes (see step 4 in execution_table), g data is cleared automatically.
Can g.user be shared between different requests?
No, each request gets a new g object. Sharing data between requests requires other methods like sessions or databases.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of g.user at Step 3?
A'Alice'
BNone
C'Bob'
DUndefined
💡 Hint
Check the 'g.user value' column at Step 3 in the execution_table.
At which step does the g object get cleared?
AStep 2
BStep 4
CStep 3
DNever
💡 Hint
Look at the 'Action' and 'g.user value' columns in the execution_table for Step 4.
If we did not set g.user in before_request, what would index() return?
A'Hello, None!'
B'Hello, !'
CError because g.user is missing
D'Hello, g.user!'
💡 Hint
g.user is not set, so accessing it raises AttributeError.
Concept Snapshot
Flask's g object stores data only during one request.
Use g to save info like current user or db connection.
Set g values in before_request or view functions.
Data in g is cleared after request ends.
Do not use g for data sharing between requests.
Full Transcript
In Flask, the g object is a special place to store data that lasts only during one web request. When a request starts, Flask creates a fresh g object. You can put information there, like the current user or database connection, so different parts of your code can access it easily. For example, in a before_request function, you can save the user from the request headers into g.user. Then, in your route function, you read g.user to personalize the response. After the request finishes, Flask clears g automatically, so the data does not leak into other requests. This makes g perfect for temporary, request-scoped data but not for sharing data between requests.

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

  1. Step 1: Understand the scope of g

    The g object is designed to hold data only during the life of one request.
  2. Step 2: Compare with other storage options

    Unlike session or global variables, g does not persist data beyond the current request.
  3. Final Answer:

    To store data temporarily during a single request -> Option A
  4. 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

  1. Step 1: Recall how to assign attributes in g

    g acts like a simple object where you assign attributes using dot notation.
  2. 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.
  3. Final Answer:

    g.user = 'Alice' -> Option A
  4. Quick Check:

    Use dot notation to set g attributes [OK]
Hint: Use dot notation: g.attribute = value [OK]
Common Mistakes:
  • Using dictionary syntax like g['key']
  • Trying to call non-existent methods on g
  • Confusing g with Flask's session object
3. Consider this Flask code snippet:
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?
medium
A. 10
B. 5
C. 15
D. Error: AttributeError

Solution

  1. Step 1: Understand the before_request function

    Before each request, g.value is set to 10.
  2. Step 2: Analyze the index function

    It adds 5 to g.value, making it 15, then returns it as a string.
  3. Final Answer:

    15 -> Option C
  4. 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

  1. Step 1: Understand g scope

    g is reset for each request, so counter does not persist between requests.
  2. Step 2: Analyze the counter behavior

    Each request starts fresh, so counter is set to 0 then incremented to 1 every time.
  3. Final Answer:

    The counter resets on every request, so it always returns 1 -> Option D
  4. 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

  1. Step 1: Analyze the get_db function

    It checks if g.db exists; if not, it opens the connection and saves it to g.
  2. Step 2: Understand request scope of g

    The connection is stored only for the current request, so multiple calls reuse the same connection.
  3. 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.
  4. Final Answer:

    It shares one connection per request, avoiding multiple opens -> Option B
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard