g Object (Flask)

g is Flask's 'global' namespace object for stashing data during a single request, such as the current user or a database connection. Despite the name it is request-scoped — it resets at the start of every request.

Flask

g gives you a scratchpad that any function handling the current request can read and write without passing values around. A typical use is loading the current user once in a before_request hook and storing it on g.user so every view can use it.

The crucial nuance is its lifetime: g lives only for the current application context (effectively the current request) and is cleared between requests. It is not shared between users or requests, so it is safe even with concurrency, but it is the wrong place for anything that should persist.

Common patterns include lazily caching a resource: define get_db() that returns g.db, creating it on first access, and tearing it down in a teardown_appcontext handler.

Syntax

from flask import g
g.user = current_user

Examples

Python

from flask import g

@app.before_request
def load_user():
    g.user = session.get("user", "anonymous")

@app.route("/whoami")
def whoami():
    return g.user

Learn it in a lesson

See also

Back to the Dictionary