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

← All Flask questions