Performance: G object for request-scoped data
This affects how data is stored and accessed during a single web request, impacting memory usage and request handling speed.
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}"
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}"
| Pattern | Memory Usage | Request Time | Server Load | Verdict |
|---|---|---|---|---|
| Repeated function calls without G | Low per call but repeated | High due to duplicate DB queries | Higher due to redundant work | [X] Bad |
| Caching data in G object | Slightly higher per request | Lower by avoiding repeats | Lower due to efficient reuse | [OK] Good |
g object in Flask?gg object is designed to hold data only during the life of one request.g does not persist data beyond the current request.g = request-scoped storage [OK]g lasts only for one request [OK]g stores data across requestsg with session or global variablesg manages database connections automaticallyg object inside a Flask view function?gg acts like a simple object where you assign attributes using dot notation.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.g attributes [OK]g.attribute = value [OK]g['key']gg with Flask's session objectfrom 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)before_request functiong.value is set to 10.index functiong.value, making it 15, then returns it as a string.g.value starts 10, adds 5 = 15 [OK]g resets each request; additions apply after setup [OK]g.value keeps old values between requestsbefore_request runs before routeg? 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)g scopeg is reset for each request, so counter does not persist between requests.counter is set to 0 then incremented to 1 every time.g data is request-scoped, no persistence [OK]g resets each request; no data persists [OK]g.counter to keep increasing across requestsg forbids new attributesg with session or global variablesg. 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'get_db functiong.db exists; if not, it opens the connection and saves it to g.gg is not global. It closes the connection automatically after each function is incorrect; closing is not automatic here.g to cache per-request resources [OK]g to reuse during request [OK]g stores data globally across requestsg auto-closes resourcesPass the test and this pattern moves unknown