首先,如果您返回 Jinja2 模板,您应该返回TemplateResponse
,如图所示文档。要将用户重定向到特定页面,您可以使用重定向响应。由于您通过 POST(而不是 GET)方法执行此操作,如示例所示,405 (Method Not Allowed)
将会抛出错误。不过还是感谢@tiangolo, 你可以更改响应状态码 to status_code=status.HTTP_303_SEE_OTHER
,然后问题就会得到解决。下面是一个工作示例。如果您需要通过额外的path and/or query您的端点的参数,请查看this and this也回答一下。
工作示例
app.py
from fastapi import FastAPI, Request, Form, status
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse
app = FastAPI()
templates = Jinja2Templates(directory="templates")
# replace with your own get_students() method
def get_students():
return ["a", "b", "c"]
@app.post('/add')
async def add(request: Request, name: str = Form(...), surname: str = Form(...), _class: str = Form(...)):
# add_student(name, surname, _class) # Adding student data
redirect_url = request.url_for('index')
return RedirectResponse(redirect_url, status_code=status.HTTP_303_SEE_OTHER)
@app.get('/add_student')
async def add_student_page(request: Request):
return templates.TemplateResponse("add_student.html", {"request": request})
@app.get('/')
async def index(request: Request):
students = get_students() # Get a list of students
return templates.TemplateResponse("index.html", {"request": request, "students": students})
模板/索引.html
<!DOCTYPE html>
<html>
<body>
<h1>Students: {{ students }}</h1>
</body>
</html>
模板/add_student.html
<!DOCTYPE html>
<html>
<body>
<form action="http://127.0.0.1:8000/add" method="POST">
name : <input type="text" name="name"><br>
surname : <input type="text" name="surname"><br>
class : <input type="text" name="_class"><br>
<input type="submit" value="submit">
</form>
</body>
</html>