What is Flask's application context and request context?

Answer

Flask has two contexts that make certain objects globally accessible during request handling. Application Context: pushed when the app starts handling a request or when explicitly entered. Provides access to g (request-scoped storage for sharing data between functions in one request) and current_app (proxy to the Flask app). Request Context: pushed for each incoming request. Provides request (the current HTTP request object with request.args, request.json, request.headers) and session (cookie-based session). Flask uses thread-local proxies to make these available globally without passing them around. In testing, manually push contexts: with app.app_context():. Understanding contexts is crucial for avoiding the common RuntimeError: Working outside of application context error.