fastapi:第二十二章:模板中的选择结构和循环结构
一,选择结构
python代码:
# app/api/users.py
from fastapi import APIRouter, Depends
from starlette.requests import Request
from starlette.templating import Jinja2Templates
from app.core.Settings import get_settings
from app.core.templates import templates
from app.middleware.log_single_route import log_this_route
# 创建路由器实例
# prefix:所有路由的统一前缀,避免重复写"/users"
# tags:在Swagger文档中分组显示
router = APIRouter(prefix="/users", tags=["用户管理"])
@router.get("/one")
def get_user(request: Request,user_id: int = 1,name: str = None):
"""根据ID获取单个用户"""
# print(name)
return templates.TemplateResponse(
request = request,
name="user_all.html",
context={"username": f"{name}", "title": "象牙山村委会"}
)
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, {{ username }}!</h1>
{% if username == '谢广坤' %}
<p>世界第一作精</p>
{% elif username == '赵四' %}
<p>亚洲舞王,尼古拉斯</p>
{% else %}
<p>刘能:象牙山小诸葛</p>
{% endif %}
<p>Welcome to your FastAPI web application.</p>
</body>
</html>
测试效果:

二,循环结构
python代码:
@router.get("/one")
def get_user(request: Request,user_id: int = 1,name: str = None):
"""根据ID获取单个用户"""
users = ['王大拿','马大帅','王富贵']
books = [
{
'name': '三国演义',
'author': '罗贯中',
'price': 110
}, {
'name': '西游记',
'author': '吴承恩',
'price': 109
}, {
'name': '红楼梦',
'author': '曹雪芹',
'price': 120
}, {
'name': '水浒传',
'author': '施耐庵',
'price': 119
}
]
return templates.TemplateResponse(
request = request,
name="user_all.html",
context = {"users": users, "books": books, "title": "象牙山村委会"}
)
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<ul>
{% for user in users|reverse %}
<li>{{ user }}</li>
{% else %}
<li>沒有任何值</li>
{% endfor %}
</ul>
<table>
<thead>
<tr>
<th>序号</th>
<th>书名</th>
<th>作者</th>
<th>价格</th>
<th>总数</th>
</tr>
</thead>
<tbody>
{% for book in books %}
{% if loop.first %}
<tr style="background: red;">
{% elif loop.last %}
<tr style="background: pink;">
{% else %}
<tr>
{% endif %}
<td>{{ loop.index0 }}</td>
<td>{{ book.name }}</td>
<td>{{ book.author }}</td>
<td>{{ book.price }}</td>
<td>{{ loop.length }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
测试效果:

浙公网安备 33010602011771号