在 Flask 中,路由 (Route) 是将 URL 地址映射到特定的视图函数 (View Function) 的机制。视图函数处理用户请求,并返回 HTTP 响应。理解路由和视图函数是构建 Flask 应用的基础。
3.1 路由的基本概念
Flask 使用 @app.route() 装饰器来定义路由。以下是一个最简单的路由示例:
python
from flask import Flask
app = Flask(__name__)
@app.route('/')def home():
return "Welcome to Flask!"
if __name__ == '__main__':
app.run(debug=True)
访问 http://127.0.0.1:5000/ 时,浏览器会显示 "Welcome to Flask!"。
3.2 定义路由规则
3.2.1 静态 URL 路由
python
@app.route('/about')
def about():
return "This is the about page"
访问 http://127.0.0.1:5000/about,会显示 "This is the about page"。
3.2.2 动态 URL 路由
Flask 允许在 URL 中传递参数。例如:
python
@app.route('/user/<username>')
def user_profile(username):
return f"Hello, {username}!"
访问 http://127.0.0.1:5000/user/Alice,会返回 "Hello, Alice!"。
3.2.3 指定变量类型
Flask 支持多种 URL 变量类型:
python
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f"Post ID: {post_id}"
@app.route('/price/<float:amount>')
def show_price(amount):
return f"Price: ${amount:.2f}"
访问 http://127.0.0.1:5000/post/123,返回 "Post ID: 123"。
访问 http://127.0.0.1:5000/price/9.99,返回 "Price: $9.99"。
支持的类型包括:
- <int:var>:整数
- <float:var>:浮点数
- <string:var>:字符串(默认)
- <path:var>:包含 / 的字符串
3.2.4 使用 path变量匹配多级路径****
python
@app.route('/files/<path:filepath>')
def get_file(filepath):
return f"File path: {filepath}"
访问 http://127.0.0.1:5000/files/docs/python.pdf,返回 "File path: docs/python.pdf"。
3.3 处理 HTTP 请求方法
默认情况下,Flask 视图函数仅处理 GET 请求。可以使用 methods 参数指定允许的请求类型:
python
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
return "Form submitted via POST"
return "Submit a form using POST"
访问 http://127.0.0.1:5000/submit 时,默认返回 "Submit a form using POST"。
使用 POST 方式提交表单时,返回 "Form submitted via POST"。
3.4 视图函数的返回值
3.4.1 返回字符串
python
@app.route('/hello')
def hello():
return "Hello, Flask!"
3.4.2 返回 HTML 代码
python
@app.route('/html')
def html():
return "<h1>Welcome</h1><p>This is an HTML response.</p>"
3.4.3 返回 JSON 数据
python
from flask import jsonify
@app.route('/json')
def json_response():
return jsonify({"message": "Hello, JSON", "status": 200})
访问 http://127.0.0.1:5000/json,返回:
{
"message": "Hello, JSON",
"status": 200
}
3.4.4 自定义 HTTP 响应
python
from flask import Response
@app.route('/custom_response')
def custom_response():
return Response("Custom Response", status=202, mimetype='text/plain')
返回的 HTTP 头信息包含:
HTTP/1.1 202 Accepted
Content-Type: text/plain
3.5 使用 url_for()生成 URL
url_for() 用于动态生成 URL,而不是硬编码 URL,保证可维护性。
python
from flask import url_for
@app.route('/profile/<username>')
def profile(username):
return f"User: {username}"
@app.route('/user-url')
def user_url():
return url_for('profile', username='John', _external=True)
访问 http://127.0.0.1:5000/user-url,返回:
http://127.0.0.1:5000/profile/John
3.6 使用 Blueprint组织路由****
在大型应用中,使用 Blueprint 组织路由,提高可维护性。
3.6.1 定义Blueprint
创建 app/routes.py:
python
from flask import Blueprint
main = Blueprint('main', __name__)
@main.route('/')
def home():
return "Welcome to Flask Blueprint!"
@main.route('/contact')
def contact():
return "Contact Page"
3.6.2 在 app/init.py中注册**Blueprint**
python
from flask import Flask
from app.routes import main
def create_app():
app = Flask(__name__)
app.register_blueprint(main)
return app
这样,所有路由都被组织在 Blueprint 中,提高了可扩展性。
3.7 路由的错误处理
3.7.1 处理 404 错误
python
@app.errorhandler(404)
def page_not_found(error):
return "This page does not exist", 404
访问一个不存在的页面时,会返回 "This page does not exist",并带有 404 状态码。
3.7.2 处理 500 内部服务器错误
python
@app.errorhandler(500)
def internal_server_error(error):
return "Internal Server Error", 500
3.8 结语
本章介绍了 Flask 的路由机制、视图函数、请求方法处理、Blueprint 组织结构以及错误处理。在下一章,我们将深入探讨 Flask 的模板系统。