from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to the Home Page!'
@app.route('/user/' )
def user_profile(username):
return f'用户:{username}'
访问 http://localhost:5000/user/zhangsan,会返回:
用户:zhangsan
类型规则:
类型 | 示例 | |
---|---|---|
(默认) |
/user/ |
匹配任意字符串 |
|
/post/ |
匹配整数值 |
|
/rate/ |
匹配浮点数值 |
|
/file/ (可含 / ) |
匹配任意字符,包括斜杠 /。 |
实例
@app.route('/user/' )
def user_profile(user_id):
return f'User ID: {user_id}'
@app.route('/files/' )
def serve_file(filename):
return f'Serving file: {filename}'
Flask 路由支持不同的 HTTP 请求方法,如 GET、POST、PUT、DELETE 等。可以通过 methods 参数指定允许的请求方法。
默认只允许 GET,要支持 POST 必须显式声明
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return '处理登录'
return '显示登录页面'
视图函数可以返回多种类型的响应:
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 页面。
静态文件访问:
"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'{url_for("profile")}">进入资料页'
模板文件渲染:
from flask import render_template
@app.route('/hello/' )
def hello(name):
return render_template('hello.html', name=name)
模板文件 (templates/hello.html):
DOCTYPE html>
<html>
<head>
<title>Hellotitle>
head>
<body>
<h1>Hello, {{ name }}!h1>
body>
html>
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>