Flask 的两大核心功能:
- 路由(Routing):URL 与 Python 函数的映射
- 模板(Template):Jinja2 模板系统,用于渲染 HTML 页面
你会学到如何构建网页、传值、模板继承、静态文件等核心知识。
第一部分:Flask 路由(Routing)
1. 路由是什么?
路由定义 URL 地址应该由哪个函数来处理:
python
@app.route('/hello')
def hello():
return "Hello Flask!"
访问:
arduino
http://127.0.0.1:5000/hello
2. 基本路由写法
python
@app.route('/')
def index():
return "首页"
3. 路由参数
Flask 可以在 URL 中接收变量。
字符串参数(默认)
python
@app.route('/user/<name>')
def user(name):
return f"Hello, {name}"
访问: /user/Alice
转换器(int / float / path 等)
| 类型 | 用途 |
|---|---|
string |
默认类型 |
int |
整数 |
float |
小数 |
path |
包含 / 的路径 |
uuid |
UUID 类型 |
示例:
python
@app.route('/add/<int:a>/<int:b>')
def add(a, b):
return str(a + b)
4. HTTP 方法限制(GET / POST 等)
python
@app.route('/login', methods=['GET', 'POST'])
def login():
return "login"
5. URL 反向生成(url_for)
推荐使用 url_for(),避免硬编码 URL。
python
from flask import url_for
@app.route('/home')
def home():
return url_for('home') # "/home"
在模板中也可以使用:
html
<a href="{{ url_for('home') }}">首页</a>
第二部分:模板系统(Jinja2)
Flask 默认使用 Jinja2 模板引擎,功能强大、安全、灵活。
1. 模板目录结构
Flask 会自动在 templates/ 中寻找模板。
markdown
project/
app.py
templates/
index.html
about.html
2. 最简单的模板渲染
python
from flask import render_template
@app.route('/page')
def page():
return render_template("index.html")
templates/index.html:
html
<h1>Hello Template</h1>
3. 模板变量传递
python
@app.route('/user/<name>')
def user(name):
return render_template("user.html", username=name)
templates/user.html:
html
<h1>Hello {{ username }}</h1>
4. 模板中的控制语句
条件判断
html
{% if vip %}
<p>尊贵的VIP用户</p>
{% else %}
<p>普通用户</p>
{% endif %}
✔ 循环
html
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
5. Jinja2 过滤器(Filters)
常用过滤器:
html
{{ "hello"|upper }} <!-- HELLO -->
{{ 3.14159|round(2) }} <!-- 3.14 -->
6. 模板继承(推荐)
非常强大,可以避免重复 HTML。
✔ base.html(母版模板)
templates/base.html:
html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Flask Demo{% endblock %}</title>
</head>
<body>
<div class="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
子模板继承
templates/index.html:
html
{% extends "base.html" %}
{% block title %}首页{% endblock %}
{% block content %}
<h1>欢迎来到首页</h1>
{% endblock %}
7. 静态文件使用(CSS/JS/图片)
默认目录:static/
arduino
project/
static/
style.css
模板中:
html
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
8. 将数据传给前端模板(综合示例)
app.py:
python
@app.route('/products')
def products():
items = ["电脑", "手机", "耳机"]
return render_template("products.html", items=items, vip=True)
products.html:
html
{% extends "base.html" %}
{% block content %}
<h1>商品列表</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% if vip %}
<p>VIP用户享受9折优惠!</p>
{% endif %}
{% endblock %}
总结
你已经掌握了 Flask Web 开发的核心:
✔ 路由系统
- 定义 URL
- 路由参数
- HTTP 方法
url_for反向解析
✔ 模板系统(Jinja2)
- 加载模板
- 传递变量
- 条件 / 循环
- 模板继承
- 静态文件加载
完全可以开发一个小型的 Web 网站或管理后台了!