Flask - Request Object
Flask – The Request Object
Section titled “Flask – The Request Object”When a client (like a web browser or another application) sends a request to your Flask application, Flask makes all the information about that request available through a global context local object called request. To use it in your view functions, you need to import it from the flask module.
from flask import Flask, request
app = Flask(__name__)
@app.route('/process', methods=['GET', 'POST'])def process_request(): # Access request data here using the 'request' object user_agent = request.headers.get('User-Agent') http_method = request.method # ... process other request attributes ... return f"Request Method: {http_method}, User Agent: {user_agent}"Important Attributes of the request Object:
Section titled “Important Attributes of the request Object:”request.method: The HTTP method used for the request (e.g.,'GET','POST','PUT','DELETE'). Crucial for distinguishing between different actions on the same URL.request.form: A dictionary-like object (ImmutableMultiDict) containing the parsed data from a submitted HTML form (typically sent via POST or PUT requests withContent-Type: application/x-www-form-urlencodedormultipart/form-data). Keys correspond to thenameattributes of form elements.request.args: A dictionary-like object (ImmutableMultiDict) containing the parsed contents of the URL’s query string (the part after the?). Commonly used to pass parameters in GET requests (e.g.,/search?query=flask).request.values: A combined dictionary-like object containing data from bothrequest.formandrequest.args. It’s generally better to useformorargsdirectly for clarity.request.json: If the request’s mimetype isapplication/json, this attribute contains the parsed JSON data sent in the request body. ReturnsNoneif the mimetype is different or parsing fails. Essential for building APIs.request.files: A dictionary-like object (ImmutableMultiDict) containing file objects for any files uploaded via an HTML form (<input type="file">). Keys correspond to thenameattribute of the file input.request.cookies: A dictionary containing the cookies sent by the client.request.headers: A dictionary-like object containing the request headers (e.g.,User-Agent,Content-Type,Accept). Access headers usingrequest.headers.get('Header-Name').request.remote_addr: The IP address of the client making the request. (Note: Can be unreliable if behind proxies).request.url: The full URL requested by the client.
Example: Accessing Form Data and Query Parameters
Section titled “Example: Accessing Form Data and Query Parameters”from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/login', methods=['GET', 'POST'])def login(): if request.method == 'POST': # Access form data submitted via POST username = request.form.get('username') # Use .get() to avoid KeyError if missing password = request.form.get('password') # In a real app: validate credentials if username and password: return f'Login successful for user: {username}' else: return 'Login failed: Missing username or password.', 400 else: # GET request # Access query parameters (e.g., /login?error=credentials) error_message = request.args.get('error') # Render the login form (assuming you have login.html template) return render_template('login_form.html', error=error_message)
# A simple template templates/login_form.html:# <!DOCTYPE html># <html><body># <h1>Login</h1># {% if error %}<p style="color: red;">Error: {{ error }}</p>{% endif %}# <form method="post"># Username: <input type="text" name="username"><br># Password: <input type="password" name="password"><br># <input type="submit" value="Login"># </form># </html></body>
if __name__ == '__main__': app.run(debug=True)Understanding ImmutableMultiDict:
Section titled “Understanding ImmutableMultiDict:”Attributes like request.form and request.args are instances of ImmutableMultiDict. This means they behave like dictionaries, but they can hold multiple values for the same key (e.g., from multiple checkboxes with the same name). If you access a key like request.form['key'], you get the first value associated with that key. To get all values, use the getlist('key') method.
The request object is fundamental for handling client input and understanding the context of incoming requests in your Flask application.