This document explains the Flask request and response objects, their attributes, and how to handle HTTP methods, headers, query parameters, and custom responses in Flask web applications.
This document explores how Flask handles HTTP requests and responses, including the use of the request and response objects, their key attributes, and methods for extracting and sending data. It covers HTTP method handling, headers, query parameters, and custom responses in Flask applications.
Flask provides two essential objects for handling web communication: the request object and the response object. These objects allow applications to receive data from clients and send data back, supporting a wide range of HTTP methods and custom behaviors.
Routes in Flask are defined using the @app.route decorator. By default, routes respond to GET requests, but the methods argument can be used to specify other HTTP methods such as POST.
1@app.route('/health', methods=['GET', 'POST'])
2def health():
3 if request.method == 'GET':
4 return {'status': 'OK', 'method': 'GET'}
5 elif request.method == 'POST':
6 return {'status': 'OK', 'method': 'POST'}
This example shows a route that responds to both GET and POST requests, returning different responses based on the method used.
The request object, created from the Flask.request class, contains all information sent by the client. Key attributes include:
| Attribute | Description |
|---|---|
| host, port | Server address as a tuple |
| headers | All headers sent with the request |
| url | The requested resource URL |
| access_route | List of IP addresses for forwarded requests |
| full_path | Complete path including query string |
| is_secure | True if HTTPS or WSS is used |
| is_json | True if the request contains JSON data |
| cookies | Dictionary of cookies sent with the request |
| Header | Purpose |
|---|---|
| Cache-Control | Browser caching information |
| Accept | Content types accepted by the client |
| Accept-Encoding | Accepted content encodings |
| User-Agent | Client application, OS, or version |
| Accept-Language | Preferred language and locale |
| Host | Host and port of the requested server |
Flask provides several methods to extract data from requests:
request.args: Query parameters as a dictionaryrequest.json: JSON data parsed into a dictionaryrequest.files: Uploaded filesrequest.form: Form submission valuesrequest.values: Combines args and form dataThe return types for these methods are usually MultiDict, ImmutableMultiDict, or CombinedMultiDict, which behave like Python dictionaries.
1from flask import Flask, request
2
3@app.route('/course')
4def course_info():
5 course = request.args['course'] # Raises error if missing
6 rating = request.args.get('rating') # Returns None if missing
7 return {'course': course, 'rating': rating}
The response object is used to send data back to the client. It includes attributes such as:
| Attribute | Description |
|---|---|
| status_code | Indicates success or failure of the request |
| headers | Additional information about the response |
| content_type | Media type of the response |
| content_length | Size of the response body |
| content_encoding | Encoding applied to the response |
| mimetype | Media type of the response |
| expires | Expiry date/time of the response |
set_cookie: Sets a browser cookie on the clientdelete_cookie: Deletes a cookie on the clientmake_response: Creates a custom responseredirect: Returns a 302 status code and redirects the clientabort: Returns a response with an error condition1from flask import make_response
2
3@app.route('/custom')
4def custom():
5 response = make_response('Custom Response', 200)
6 response.headers['Content-Type'] = 'text/html'
7 return response
Flask’s request and response objects provide a flexible interface for handling HTTP communication. The request object allows access to all client-sent data, while the response object enables custom responses, headers, and status codes. Understanding these objects is essential for building robust Flask web applications.
is_secure attribute of the Flask request object is True if the request was made using HTTPS or WSS protocol.(2) The response object is used to send data, status codes, and headers back to the client in Flask applications.
| Attribute | Description |
|---|---|
| A. access_route | 1. True if the request contains JSON data |
| B. is_json | 2. List of IP addresses for forwarded requests |
| C. full_path | 3. Complete path including query string |
| D. cookies | 4. Dictionary of cookies sent with the request |
A-2, B-1, C-3, D-4.
(2) The response object can return various content types, not just plain text.
The request object in Flask allows access to both query parameters and form data through the values attribute.
True. The values attribute combines args and form data for easy access.