警察反恐射击mod内置菜单
64.36MB · 2025-11-20
Flask 的两大核心功能:
你会学到如何构建网页、传值、模板继承、静态文件等核心知识。
路由定义 URL 地址应该由哪个函数来处理:
@app.route('/hello')
def hello():
return "Hello Flask!"
访问:
http://127.0.0.1:5000/hello
@app.route('/')
def index():
return "首页"
Flask 可以在 URL 中接收变量。
@app.route('/user/<name>')
def user(name):
return f"Hello, {name}"
访问:
/user/Alice
| 类型 | 用途 |
|---|---|
string | 默认类型 |
int | 整数 |
float | 小数 |
path | 包含 / 的路径 |
uuid | UUID 类型 |
示例:
@app.route('/add/<int:a>/<int:b>')
def add(a, b):
return str(a + b)
@app.route('/login', methods=['GET', 'POST'])
def login():
return "login"
推荐使用 url_for(),避免硬编码 URL。
from flask import url_for
@app.route('/home')
def home():
return url_for('home') # "/home"
在模板中也可以使用:
<a href="{{ url_for('home') }}">首页</a>
Flask 默认使用 Jinja2 模板引擎,功能强大、安全、灵活。
Flask 会自动在 templates/ 中寻找模板。
project/
app.py
templates/
index.html
about.html
from flask import render_template
@app.route('/page')
def page():
return render_template("index.html")
templates/index.html:
<h1>Hello Template</h1>
@app.route('/user/<name>')
def user(name):
return render_template("user.html", username=name)
templates/user.html:
<h1>Hello {{ username }}</h1>
{% if vip %}
<p>尊贵的VIP用户</p>
{% else %}
<p>普通用户</p>
{% endif %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
常用过滤器:
{{ "hello"|upper }} <!-- HELLO -->
{{ 3.14159|round(2) }} <!-- 3.14 -->
非常强大,可以避免重复 HTML。
templates/base.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:
{% extends "base.html" %}
{% block title %}首页{% endblock %}
{% block content %}
<h1>欢迎来到首页</h1>
{% endblock %}
默认目录:static/
project/
static/
style.css
模板中:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
app.py:
@app.route('/products')
def products():
items = ["电脑", "手机", "耳机"]
return render_template("products.html", items=items, vip=True)
products.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_for 反向解析完全可以开发一个小型的 Web 网站或管理后台了!
64.36MB · 2025-11-20
617.38MB · 2025-11-20
155.3M · 2025-11-20