0
0
Flaskframework~8 mins

G object for request-scoped data in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: G object for request-scoped data
MEDIUM IMPACT
This affects how data is stored and accessed during a single web request, impacting memory usage and request handling speed.
Storing and accessing data during a single request lifecycle
Flask
from flask import g

def get_user():
    if not hasattr(g, 'user'):
        g.user = compute_user_from_db()
    return g.user

@app.route('/')
def index():
    user1 = get_user()
    user2 = get_user()
    return f"Hello {user1.name} and {user2.name}"
Caches the user data in the request-scoped G object, avoiding repeated database calls.
📈 Performance GainSaves 50-100ms by reducing duplicate DB queries per request
Storing and accessing data during a single request lifecycle
Flask
def get_user():
    user = compute_user_from_db()
    return user

@app.route('/')
def index():
    user1 = get_user()
    user2 = get_user()
    return f"Hello {user1.name} and {user2.name}"
Calling the same expensive function multiple times per request causes repeated database queries and slows response.
📉 Performance CostBlocks rendering for extra 50-100ms per repeated call depending on DB latency
Performance Comparison
PatternMemory UsageRequest TimeServer LoadVerdict
Repeated function calls without GLow per call but repeatedHigh due to duplicate DB queriesHigher due to redundant work[X] Bad
Caching data in G objectSlightly higher per requestLower by avoiding repeatsLower due to efficient reuse[OK] Good
Rendering Pipeline
The G object stores data in memory during the request lifecycle, so it mainly affects server-side request processing before the response is sent.
Request Handling
Server Processing
⚠️ BottleneckRepeated expensive computations or database calls without caching
Core Web Vital Affected
INP
This affects how data is stored and accessed during a single web request, impacting memory usage and request handling speed.
Optimization Tips
1Cache expensive computations or database calls in the G object during a request.
2Avoid calling the same function multiple times without caching in G.
3Use G only for data valid during a single request to prevent memory leaks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using Flask's G object for request-scoped data?
AAvoids repeating expensive computations during the same request
BReduces the size of the final HTML sent to the client
CImproves browser rendering speed by caching CSS
DAllows sharing data between different user sessions
DevTools: Network and Performance panels
How to check: Record a request in Performance panel and look for repeated database or function call durations; check Network panel for request timing.
What to look for: Look for duplicated long-running calls or delays in server response time indicating redundant processing.