When developing web applications with Flask, we often need to return different types of responses based on various scenarios. For example, returning JSON data to the frontend API or automatically redirecting users from an old page to a new one. In such cases, Flask’s response object features like jsonify and redirect are essential.
1. Returning JSON Data¶
In web development, API endpoints typically return data in JSON format. If you directly return a Python dictionary, Flask will treat it as a regular string, making it impossible for the frontend to parse correctly. Thus, the jsonify function is necessary.
Why Use jsonify?¶
- Automatic Response Headers:
jsonifyautomatically sets theContent-Type: application/jsonheader, indicating to the frontend that the data is in JSON format. - Handle Complex Data: It supports Python data structures like dictionaries and lists, converting them into standard JSON format seamlessly.
Example Code¶
from flask import Flask, jsonify
app = Flask(__name__)
# API endpoint returning JSON data
@app.route('/api/info')
def get_info():
# Define a Python dictionary (or list)
data = {
"name": "Flask",
"version": "2.3.3",
"features": ["Lightweight", "Flexible", "Extensible"]
}
# Return JSON response using jsonify
return jsonify(data)
Incorrect Example¶
Directly returning a dictionary will result in incorrect response format:
@app.route('/api/info')
def get_info():
data = {"name": "Flask"}
return data # Error! Returns a string instead of JSON, causing frontend parsing issues
2. Redirection (Redirect)¶
When users need to be redirected to a new URL (e.g., old page migration, post-form-submission), use the redirect function to generate a redirect response.
Why Use redirect?¶
- Browser Navigation: Uses an HTTP status code (default: 302) to inform the browser, “This URL has moved; please visit the new address.”
- Prevent Duplicate Submissions: For example, after form submission, redirect to the result page to avoid duplicate submissions.
Example Code¶
from flask import Flask, redirect, url_for
app = Flask(__name__)
# Old page redirecting to the new page
@app.route('/old-page')
def old_page():
# Use url_for to dynamically get the new page's URL (avoids hardcoding)
return redirect(url_for('new_page'), code=302) # code=302 for temporary redirect
# New page
@app.route('/new-page')
def new_page():
return "Welcome to the new page!"
Status Code Explanation¶
- 302 (Temporary Redirect): Search engines may not consider the original URL permanently invalid; used for temporary redirects (e.g., event pages).
- 301 (Permanent Redirect): Search engines will record the URL change; used for permanent scenarios (e.g., domain migration).
Example:return redirect(url_for('new_page'), code=301)
3. Comprehensive Example: Redirect + JSON Response¶
from flask import Flask, jsonify, redirect, url_for, request
app = Flask(__name__)
# 1. Simulate user login form
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
# Simple validation (replace with database checks in production)
if username == "admin" and password == "123456":
# On successful login, redirect to home page
return redirect(url_for('home'))
else:
return "Incorrect username or password!"
# Render login form for GET requests
return '''
<form method="post">
<input type="text" name="username" placeholder="Username"><br>
<input type="password" name="password" placeholder="Password"><br>
<button type="submit">Login</button>
</form>
'''
# 2. Return JSON data after successful login
@app.route('/home')
def home():
user_info = {
"username": "admin",
"role": "Administrator",
"status": "Logged in"
}
return jsonify(user_info) # Return user info as JSON
if __name__ == '__main__':
app.run(debug=True)
Summary¶
- Returning JSON: Use
jsonifyto handle formatting and headers automatically, preventing frontend parsing errors. - Redirection: Use
redirectwithurl_forto avoid hardcoding URLs. Choose between 301 (permanent) or 302 (temporary) based on the scenario. - Key Difference:
jsonify“returns data,” whileredirect“changes the address,” serving distinct use cases.
With these tools, Flask can flexibly handle API data responses and page navigation, meeting most web development needs.