Flask Application Globals - g Object API
g is a request-level global namespace used to share data among multiple functions within the same request.
Imported via from flask import g, and available only while an application context is active.
g Object Description
| Feature | Description |
|---|---|
| Type | An instance of flask.ctx._AppCtxGlobals |
| Lifetime | Created with the application context and destroyed with it |
| Thread Safety | Each request/context has its own independent g object |
| Usage | Read and write attributes like a normal object: g.user = ..., g.db = ... |
_AppCtxGlobals Methods
| Method | Description |
|---|---|
| get(name, default=None) | Gets an attribute value, returning a default value if the attribute does not exist |
| pop(name, default=None) | Removes and returns an attribute value |
| setdefault(name, default=None) | If the attribute does not exist, sets a default value and returns 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
(
)
:
"""The 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 starts"""
user_id
=
session.
get
(
"user_id"
)
if
user_id:
g.
user
=
query_user
(
user_id
)
View functions can use g.user directly
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 when the request ends"""
db
=
g.
pop
(
"db"
,
None
)
if
db
is
not
None
:
db.
close
(
)
Core principles: The g object is only for data sharing within the same request. Do not store cross-request data in g, and do not store information that must be persisted in g.