Flask interview question · Most asked
What is `flask.g` and when should you use it?
Summary
g is a namespace object scoped to the application context (effectively per request) for storing data during a request, such as the current user or a lazily created DB connection.
Longer Answer
It's reset for every request, so it isn't for cross-request storage (use a cache or DB). A common pattern is a helper that creates a resource on first use and stores it on g, with teardown in @app.teardown_appcontext.
Code Example
from flask import g
def get_db():
if "db" not in g:
g.db = connect(current_app.config["DATABASE_URL"])
return g.db
@app.teardown_appcontext
def close_db(exc):
db = g.pop("db", None)
if db is not None:
db.close()
Key Points
- Per-request scratch space
- Reset each request
- Lazy resources + teardown
- Not for cross-request state
More most-asked Flask questions
- How do Flask sessions work and what are their security implications?
- What are Blueprints in Flask?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you access request data and build responses in Flask?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?