Flask
Flask.g
web development
Python
application context

When should Flask.g be used?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

flask.g is for request-scoped or application-context-scoped temporary data that should be easy to share during one request or one active app context. It is not a general global storage mechanism and it is not a long-term cache. The most common valid use is storing per-request resources such as a database connection, authenticated user lookup result, or request-local helper data.

What g Actually Is

In Flask, g is a special context-local object. Data assigned to it is available during the current request or active application context and then discarded afterward.

python
1from flask import Flask, g
2
3app = Flask(__name__)
4
5@app.route("/")
6def index():
7    g.message = "hello"
8    return g.message

This works because the route runs within Flask’s request context. Outside that context, g is not available in the same way.

Good Use Case: Per-Request Database Connection

One of the classic uses of g is storing a lazily created database connection for the duration of one request.

python
1from flask import Flask, g
2import sqlite3
3
4app = Flask(__name__)
5
6def get_db():
7    if "db" not in g:
8        g.db = sqlite3.connect("app.db")
9    return g.db
10
11@app.teardown_appcontext
12def close_db(exception):
13    db = g.pop("db", None)
14    if db is not None:
15        db.close()
16
17@app.route("/users")
18def users():
19    db = get_db()
20    rows = db.execute("select 1").fetchall()
21    return {"rows": len(rows)}

This is a strong use of g because the connection is request-local and cleanup is tied naturally to the request lifecycle.

Good Use Case: Request-Scoped User Data

If authentication middleware or a before_request hook loads the current user once, g is a natural place to put it.

python
1from flask import Flask, g, request
2
3app = Flask(__name__)
4
5@app.before_request
6def load_user():
7    token = request.headers.get("Authorization")
8    g.current_user = {"name": "ava"} if token else None
9
10@app.route("/me")
11def me():
12    if g.current_user is None:
13        return {"error": "unauthorized"}, 401
14    return g.current_user

This avoids repeated lookups and keeps request-specific state centralized.

What g Is Not For

Do not use g for:

  • cross-request caching
  • application configuration
  • persistent session data
  • background worker state
  • data you need after the request ends

Those are different lifetimes and require different storage mechanisms.

For example, configuration belongs in app.config, not g.

g Versus Session

People often confuse g with session.

Use g when:

  • the data only matters during the current request
  • you do not need it to survive to the next request

Use session when:

  • the data belongs to the user across multiple requests
  • it must persist between page loads

This lifetime difference is the real conceptual boundary.

g Versus Globals

Plain module globals are shared across requests and potentially across threads or workers. That makes them unsafe for request-local data.

g exists precisely to avoid that mistake. It gives you a convenient place for per-request state without turning the codebase into a collection of unsafe shared variables.

App Context Matters

g is tied to Flask context management. If you try to use it outside an application or request context, Flask will complain.

For example:

python
from flask import g

# accessing g here without context is invalid

In tests or scripts, you may need an app context:

python
with app.app_context():
    g.value = 123
    print(g.value)

This is one reason g should stay focused on framework-managed request or app-context lifetimes.

Keep g Small and Predictable

The existence of g does not mean every helper value should be stuffed into it. Overusing it makes request flow harder to understand because data appears from invisible side effects.

Good use is usually:

  • a small number of shared request resources
  • values set in obvious middleware or helper functions
  • cleanup-aware objects such as DB handles

If business logic everywhere starts reaching into g for unrelated data, the design usually needs tightening.

Common Pitfalls

The biggest mistake is treating g like a general global store instead of a request-scoped context object. Another is using it for data that needs to survive across requests, where session or a database would be more appropriate. Developers also often hide too much implicit state in g, which makes code paths hard to follow. Finally, accessing g outside a valid Flask context causes runtime errors that confuse people who do not yet understand request and app contexts.

Summary

  • Use flask.g for temporary request-scoped or app-context-scoped data.
  • It is a good place for per-request database connections and current-user data.
  • Do not use it for cross-request persistence or global application configuration.
  • Prefer explicit, limited use rather than storing unrelated state everywhere.
  • Remember that g only works inside a valid Flask context.

Course illustration
Course illustration

All Rights Reserved.