1.6 通过模版引擎返回HTM页面
import uvicorn
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
# 初始化模版引擎存放位置
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def index(request:Request):
return templates.TemplateResponse("index.html", context={'request': request})
if __name__ == '__main__':
uvicorn.run('main:app', port=5050, reload=True)
注释:
context参数里的’request’ key值是不能修改的,否则会报错
1.6.1 将参数传入html页面
main.py中
import uvicorn
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
# 初始化模版引擎存放位置
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def index(username, request: Request):
return templates.TemplateResponse("index.html", context={'request': request, "name": username})
if __name__ == '__main__':
uvicorn.run('main:app', port=5050, reload=True)
index.html中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p>Hello, FastApi</p>
<p>New hand with test engineer</p>
<p>用户名: {{ name }}</p>
</body>
</html>
注释:
将用户输入参数(例如:username)放入模版引擎中return(key值命名为name),在template模版中获取name,即可完成传参
1.6.2 实操
目标:实现一个小应用,在页面上点击提交按钮之后,将数据写进列表中,并在返回到前端页面上
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>事件</h1>
<p>Hello, FastApi</p>
<div>
<form action="/todo", method="post">
<input name="todo" placeholder="请添加事件。。。">
<input type="submit", value="添加">
</form>
</div>
{% for todo in todos %}
<p>{{ todo }}</p>
{% endfor %}
</body>
</html>
main.py
import uvicorn
from fastapi import FastAPI, Request, Form
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
# 初始化模版引擎存放位置
templates = Jinja2Templates(directory="templates")
todos = ['看书', '听歌', '玩游戏']
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", context={'request': request, "todos": todos})
@app.post("/todo")
async def todo(todo=Form(None)):
todos.insert(0, todo)
return RedirectResponse('/', status_code=302)
if __name__ == '__main__':
uvicorn.run('main:app', port=5050, reload=True)