Performance: Application context
Application context affects how Flask manages global variables during a request, impacting memory usage and request handling speed.
from flask import Flask, current_app app = Flask(__name__) with app.app_context(): print(current_app.config)
from flask import current_app print(current_app.config)
| Pattern | Context Creation | Memory Usage | Request Latency | Verdict |
|---|---|---|---|---|
| Implicit context access outside request | Triggers implicit context creation | Higher due to extra objects | Increases latency | [X] Bad |
| Explicit app context with 'with' block | Single explicit context creation | Lower and controlled | Minimal latency impact | [OK] Good |
with app.app_context(): syntax to push the application context safely.push_context(), context_push(), or context() do not exist in Flask's API.from flask import Flask, current_app
app = Flask(__name__)
with app.app_context():
print(current_app.name)with app.app_context():, current_app refers to the Flask app instance.Flask(__name__), so current_app.name equals the module name, which is "__main__" when run directly.from flask import Flask, current_app app = Flask(__name__) print(current_app.name)
current_app.name outside any application context.current_app without pushing an app context raises a RuntimeError because Flask doesn't know which app is active.current_app.config in this task?with app.app_context(): activates the app context, allowing safe access to current_app.config.with app.app_context(): -> Option DPass the test and this pattern moves unknown