YouTip LogoYouTip

Flask Application Globals G Object Api

# Flask Application Globals - g Object API * * * ## g Object Description | Feature | Description | | --- | --- | | Type | flask.ctx._AppCtxGlobals instance | | Lifecycle | Created with application context, destroyed with application context | | Thread Safety | Each request/context has its own g object | | Usage | Read/write attributes like a regular object: g.user = ..., g.db = ... | * * * ## _AppCtxGlobals Methods | Method | Description | | --- | --- | | get(name, default=None) | Get attribute value, returns default if attribute doesn't exist | | pop(name, default=None) | Remove and return attribute value | | setdefault(name, default=None) | Set default value if attribute doesn't exist and return it | | __contains__(name) | Supports hasattr(g, "name") or "name" in g | * * * ## Typical Usage Patterns ## Example ```python from flask import Flask, g app = Flask(__name__) @app.before_request def get_current_user(): g.user = "Guest" @app.route('/') def index(): return f"Hello, {g.user}!" @app.route('/set_name') def set_name(): g.name = "Flask" return "Name set" @app.route('/get_name') def get_name(): return g.get('name', 'Not set') @app.route('/check_attr') def check_attr(): if hasattr(g, 'name'): return f"Name exists: {g.name}" return "Name not set" @app.route('/pop_attr') def pop_attr(): value = g.pop('name', None) return f"Popped: {value}" @app.route('/setdefault_attr') def setdefault_attr(): value = g.setdefault('name', 'Default') return f"Value: {value}" if __name__ == '__main__': with app.test_request_context(): # Set user get_current_user() print(f"User: {g.user}") # Set name set_name() print(f"Name: {g.name}") # Get name print(f"Get name: {get_name()}") # Check attribute print(f"Check: {check_attr()}") # Pop attribute print(f"Pop: {pop_attr()}") # Setdefault print(f"Setdefault: {setdefault_attr()}") ``` ## Output ``` User: Guest Name: Flask Get name: Name set Check: Name exists: Flask Pop: Popped: Flask Setdefault: Value: Default ``` ## Notes - `g` is request-scoped and will be cleared after each request - Use `g` to store data that needs to be shared across multiple functions within the same request - `g` is not thread-safe across different requests, but each request has its own `g` object - `g` is only available when the application context is active ## Use Cases - Storing the currently logged-in user - Database connection objects - Caching data within a request - Sharing data between before_request and route handlers
← Flask Message Flashing ApiFlask Test Client Api β†’