In web development, requests and responses are two core concepts. Simply put, a request is data sent by a client (such as a browser) to a Flask application, while a response is the result returned by the Flask application to the client. Understanding these two objects is fundamental to mastering Flask development.
1. Request Object: Obtaining Data from the Client¶
When a user accesses a Flask route in a browser, the browser sends a request to the Flask application. Flask encapsulates this request data through the request object, which we can use to access user input, request methods, URL parameters, and more.
1. Importing the Request Object¶
To use the request object, first import it from the flask module:
from flask import Flask, request
2. Core Properties of the Request Object¶
The request object contains almost all information sent by the client. Here are the commonly used core properties:
| Property/Method | Description |
|---|---|
request.method |
Get the HTTP method (e.g., GET, POST, PUT), returned as an uppercase string |
request.args |
Get URL parameters (corresponds to GET requests, e.g., name in http://example.com/?name=test) |
request.form |
Get form data (corresponds to POST requests, e.g., data from an HTML form submission) |
request.cookies |
Get cookies sent by the client |
request.headers |
Get request headers (e.g., User-Agent, Content-Type, etc.) |
3. Example: Handling GET and POST Requests¶
app = Flask(__name__)
@app.route('/')
def index():
# Handle GET requests (URL parameters)
name = request.args.get('name', 'Guest') # Get the 'name' parameter, defaulting to 'Guest'
return f"Hello, {name}!This is the response for a GET request"
@app.route('/submit', methods=['POST'])
def submit():
# Handle POST requests (form data)
username = request.form.get('username')
password = request.form.get('password')
if username and password:
return f"Submission successful! Username: {username}"
else:
return "Username or password cannot be empty", 400 # Return 400 status code (Bad Request)
if __name__ == '__main__':
app.run(debug=True)
Testing Methods:
- Access http://localhost:5000/?name=Xiaoming, and you will get “Hello, Xiaoming!This is the response for a GET request”
- Submit data via a POST form (e.g., using Postman or an HTML form) with username=test and password=123, and you will get “Submission successful! Username: test”
2. Response Object: Returning Results to the Client¶
After Flask processes a request, it needs to return the result to the client through the response object. Flask response objects can be strings, HTML pages, JSON data, redirects, etc.
1. Returning a Simple String¶
The simplest response method: Flask automatically wraps the string into a response with a status code of 200 (Success):
@app.route('/hello')
def hello():
return "Hello, Flask!" # Default status code is 200
2. Returning an HTML Page¶
To return an HTML page, use the render_template function (you need to create a templates folder to store HTML files):
from flask import render_template
@app.route('/page')
def page():
# Render the index.html file in the templates folder
return render_template('index.html', title="Home Page")
Example templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>This is an HTML page</h1>
</body>
</html>
3. Returning JSON Data¶
To return JSON-formatted data (e.g., for API interfaces), use the jsonify function (automatically sets Content-Type: application/json):
from flask import jsonify
@app.route('/api/user')
def get_user():
user = {
"name": "Xiaohong",
"age": 20,
"hobby": "Programming"
}
return jsonify(user) # Returns JSON data with status code 200
4. Redirecting¶
To redirect to another page (e.g., redirecting to the homepage after login), use the redirect function:
from flask import redirect, url_for
@app.route('/login')
def login():
# Redirect to the homepage (url_for automatically resolves the URL corresponding to the route function)
return redirect(url_for('index'))
5. Custom Status Codes¶
By adding a status code to the return value, you can clearly indicate the result of the request to the client (e.g., 404, 500):
@app.route('/not_found')
def not_found():
return "Page not found", 404 # Status code 404: Resource not found
3. Comprehensive Example: A Simple Form Interaction¶
Here’s a complete example demonstrating the combined use of requests and responses:
from flask import Flask, request, render_template, redirect, url_for, jsonify
app = Flask(__name__)
# Homepage: Display the form (GET request)
@app.route('/')
def index():
return render_template('form.html') # Render templates/form.html
# Handle form submission (POST request)
@app.route('/submit', methods=['POST'])
def submit():
# Get form data
username = request.form.get('username')
email = request.form.get('email')
# Simple validation
if not username or not email:
return "Username and email cannot be empty!", 400 # Return error message and 400 status code
# Simulate data processing (e.g., storing in a database)
print(f"Received user data: {username}, {email}")
# Return a JSON response (could also redirect to a success page)
return jsonify({
"status": "success",
"message": f"Welcome {username}!Data received"
})
if __name__ == '__main__':
app.run(debug=True)
templates/form.html (create a templates folder in the project root directory):
<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<h1>Please fill in the information</h1>
<form method="POST" action="/submit">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="email" name="email" placeholder="Email" required><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
4. Summary¶
- Request Object (
request): Used to obtain data sent by the client. Key focus onmethod(request method),args(GET parameters), andform(POST form data). - Response Object (
response): Used to return results to the client. Common methods include strings, HTML (render_template), JSON (jsonify), and redirects (redirect). - Key Principles: GET requests are used to fetch data (parameters in the URL), while POST requests are used to submit data (parameters in the request body). Use
jsonifyfor JSON responses andrender_templatefor HTML pages.
After reading this article, you should have a basic understanding of Flask’s request and response objects. Next, try writing simple web pages or API interfaces to deepen your understanding!