Flask(二) 路由routes

发布于:2025-06-27 ⋅ 阅读:(13) ⋅ 点赞:(0)


Flask 路由是 Web 应用程序中将 URL 映射到 Python 函数的机制。

  1. 定义路由:使用 @app.route(‘/path’) 装饰器定义 URL 和视图函数的映射。
  2. 路由参数:通过动态部分在 URL 中传递参数。
  3. 路由规则:使用类型转换器指定 URL 参数的类型。
  4. 请求方法:指定允许的 HTTP 请求方法。
  5. 路由函数返回:视图函数可以返回不同类型的响应。
  6. 静态文件和模板:管理静态文件和动态渲染 HTML 模板。
  7. 路由优先级:确保路由顺序正确,以避免意外的匹配结果。

基本路由定义

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the Home Page!'

路由参数

@app.route('/user/<username>')
def user_profile(username):
    return f'用户:{username}'

访问 http://localhost:5000/user/zhangsan,会返回:

用户:zhangsan

路由规则

类型规则

类型 示例
<string:...>(默认) /user/<name> 匹配任意字符串
<int:...> /post/<int:id> 匹配整数值
<float:...> /rate/<float:x> 匹配浮点数值
<path:...> /file/<path:path>(可含 / 匹配任意字符,包括斜杠 /。

实例

@app.route('/user/<int:user_id>')
def user_profile(user_id):
    return f'User ID: {user_id}'

@app.route('/files/<path:filename>')
def serve_file(filename):
    return f'Serving file: {filename}'

设置请求方法(GET/POST)

Flask 路由支持不同的 HTTP 请求方法,如 GET、POST、PUT、DELETE 等。可以通过 methods 参数指定允许的请求方法。
默认只允许 GET,要支持 POST 必须显式声明

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return '处理登录'
    return '显示登录页面'

路由函数返回

视图函数可以返回多种类型的响应:

  • 字符串:返回纯文本响应。
  • HTML:返回 HTML 页面。
  • JSON:返回 JSON 数据。
  • Response 对象:自定义响应。
from flask import jsonify, Response

@app.route('/json')
def json_response():
    data = {'key': 'value'}
    return jsonify(data)

@app.route('/custom')
def custom_response():
    response = Response('Custom response with headers', status=200)
    response.headers['X-Custom-Header'] = 'Value'
    return response

jsonify(data):将字典转换为 JSON 响应。
Response(‘Custom response with headers’, status=200):创建自定义响应对象。

静态文件和模板

静态文件(如 CSS、JavaScript、图片)可以通过 static 路由访问。模板文件则通过 templates 文件夹组织,用于渲染 HTML 页面。

静态文件访问:

<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

使用 url_for() 生成路由链接,url_for("profile") 会生成 /profile。

@app.route('/profile')
def profile():
    return '这是你的个人资料页'

@app.route('/')
def index():
    return f'<a href="{url_for("profile")}">进入资料页</a>'

模板文件渲染:

from flask import render_template

@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)

模板文件 (templates/hello.html):

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Blueprint(模块化路由)

from flask import Blueprint

bp = Blueprint('admin', __name__, url_prefix='/admin')

@bp.route('/dashboard')
def dashboard():
    return '管理员后台'

# 注册 Blueprint
app.register_blueprint(bp)

访问 /admin/dashboard

显示当前所有路由

命令行运行:

flask routes

输出示例:

Endpoint  Methods   Rule
--------  --------  ----------------
hello     GET       /hello
static    GET       /static/<path:filename>


网站公告

今日签到

点亮在社区的每一天
去签到