0
0
Flaskframework~5 mins

G object for request-scoped data in Flask

Choose your learning style9 modes available
Introduction

The g object in Flask lets you store and share data during a single web request. It helps keep data accessible only while handling that request.

You want to save database connections to reuse during one request.
You need to share user info between different parts of your code during a request.
You want to store temporary data that should not persist after the request ends.
You want to avoid passing many variables between functions handling the same request.
Syntax
Flask
from flask import g

g.some_variable = value

# Access later in the same request
def some_function():
    print(g.some_variable)

The g object is unique for each request and resets after the request finishes.

You can add any attributes you want to g as temporary storage.

Examples
Store user info in g to access it anywhere during the request.
Flask
from flask import g

g.user = {'name': 'Alice', 'role': 'admin'}

# Later in the request
print(g.user['name'])
Save a database connection in g so it is created once per request and reused.
Flask
from flask import g

def get_db():
    if not hasattr(g, 'db'):
        g.db = connect_to_database()
    return g.db
Sample Program

This Flask app stores a fake database connection and user info in g before each request. The route then uses that data to greet the user and show the connection.

Flask
from flask import Flask, g, request

app = Flask(__name__)

def connect_to_database():
    return 'DatabaseConnectionObject'

@app.before_request
def before_request():
    g.db = connect_to_database()
    g.user = {'name': 'Bob'}

@app.route('/')
def index():
    return f"Hello {g.user['name']}! Using {g.db}"

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Do not store data in g that should persist beyond one request.

Use g to avoid global variables and keep request data isolated.

Summary

g stores data only during one request.

You can add any temporary info to g as attributes.

It helps share data between functions without globals.