When Flask receives an HTTP request, it needs a mechanism to provide necessary information, such as request headers, form data, or query parameters, to view functions. A direct approach would be to pass the request object as an argument to every view function. However, this method quickly leads to cluttered function signatures, especially as the application needs to access multiple context objects. To solve this, Flask implements contexts, a pattern that temporarily makes objects globally accessible within a specific thread.
Consider the following example. Here, a view function accesses the request object as if it were a global variable, which is made possible by the active request context.
from flask import Flask, request
# Initialize the Flask web application
web_app = Flask(__name__)
@web_app.route('/greet')
def greet_user():
# The 'request' object is accessed as if it were a global variable
# due to the active request context.
client_agent = request.headers.get('User-Agent')
return f"<p>Hello! Your browser is: {client_agent}</p>"
It's crucial to understend that the request object is not a true global variable. In a multi-threaded server environment, each thread handles a different client request. The context ensures that each thread can access its own distinct request object without interfering with others. Flask manages these contexts automaticallly during request processing.
Flask provides two types of contexts: application context and request context. The application context is activated before a request is dispatched and removed after the request is handled. When the application context is active, the current\_app and g variables become available. Similarly, when request context is active, the request and session variables become available. Attempting to use these variables when their respective context is not active will result in a runtime error.
For instance, trying to access current\_app outside of an application context will cause an error.
from flask import Flask, current_app
# Create a Flask application instance
my_app = Flask(__name__)
# This will raise an error because the application context is not active
print(my_app.name)
Output:
RuntimeError: Working outside of application context.
To access current\_app, you must manually push the application context. Using a with statement is the preferred, Pythonic way to manage the context.
from flask import Flask, current_app
# Create a Flask application instance
my_app = Flask(__name__)
# Manually push the application context to access 'current_app'
with my_app.app_context():
# Now, 'current_app' is available within this block
print(current_app.name)