路由与视图
路由把 URL 和 Python 函数(视图函数)绑定。访问对应地址,Flask 调用函数,把返回值作为响应。
基本路由
@app.route("/") 装饰器。支持 GET/POST 等方法:methods=["GET", "POST"]。
动态路由
@app.route("/user/<int:user_id>") 尖括号传参,可以限定类型:int、float、path。
URL 生成
url_for("函数名") 根据视图函数生成 URL,改路由不破坏链接。
代码示例
from flask import Flask, url_for
app = Flask(__name__)
@app.route("/")
def index():
return "首页"
@app.route("/user/<int:user_id>")
def user_detail(user_id):
return f"用户 {user_id} 的详情页"
@app.route("/post/<path:slug>")
def post(slug):
return f"文章: {slug}"
@app.route("/about")
def about():
# 用 url_for 生成首页链接
return f"关于我们 · <a href='{url_for("index")}'>返回首页</a>"
if __name__ == "__main__":
app.run(debug=True)
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |