Flask Application Globals - g Object API

gis a request-level global namespace used to share data among multiple functions within the same request.

Throughfrom flask import gImport; only available when the application context is active.


g Object Description

Features Description
Type flask.ctx._AppCtxGlobals instance
Lifecycle Created with the application context, destroyed with the application context.
Thread Safety Each request/context has its own independent g object.
Usage Read and write properties like ordinary objects: g.user = ..., g.db = ...

_AppCtxGlobals Methods

Methods Description
get(name, default=None) Get the attribute value; return the default value if the attribute does not exist.
pop(name, default=None) Remove and return the attribute value.
setdefault(name, default=None) If the attribute does not exist, set the default value and return it.
__contains__(name) Supports hasattr(g, "name") or "name" in g

Typical Usage Patterns

Example

from flask import Flask, g

app = Flask(__name__)

def get_db():
    """Database connection is created only once and stored in g for reuse"""
    if "db" not in g:
        g.db = connect_to_database()
    return g.db

@app.before_request
def load_user():
    """Load user information into g before the request begins"""
    user_id = session.get("user_id")
    if user_id:
        g.user = query_user(user_id)  # g.user can be used directly in the view function
    else:
        g.user = None

@app.route("/profile")
def profile():
    if g.user is None:
        return "Not logged in"
    return f"Hello, {g.user.name}"

@app.teardown_appcontext
def close_db(error):
    """Clean up resources at the end of the request"""
    db = g.pop("db", None)
    if db is not None:
        db.close()

Core Principles: The g object is only used for data sharing within the same request. Do not store cross-request data in g, and do not store information that needs to be persisted in g.

other extensions