文章目錄
- 基本路由定義
- 路由參數
- 路由規則
- 設置請求方法(GET/POST)
- 路由函數返回
- 靜態文件和模板
- Blueprint(模塊化路由)
- 顯示當前所有路由
Flask 路由是 Web 應用程序中將 URL 映射到 Python 函數的機制。
- 定義路由:使用 @app.route(‘/path’) 裝飾器定義 URL 和視圖函數的映射。
- 路由參數:通過動態部分在 URL 中傳遞參數。
- 路由規則:使用類型轉換器指定 URL 參數的類型。
- 請求方法:指定允許的 HTTP 請求方法。
- 路由函數返回:視圖函數可以返回不同類型的響應。
- 靜態文件和模板:管理靜態文件和動態渲染 HTML 模板。
- 路由優先級:確保路由順序正確,以避免意外的匹配結果。
基本路由定義
from flask import Flaskapp = 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 Blueprintbp = 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>