提交 HTML 表单后如何使用 FastAPI 将用户重定向回主页?

问题描述 投票:0回答:1

我有一个包含学生表格的页面。我添加了一个按钮,允许您向表中添加新行。为此,我将用户重定向到带有输入表单的页面。

问题是,提交完成的表单后,用户会转到一个新的空白页面。如何传输已完成表单中的数据并将用户重定向回表格?

我刚刚开始学习Web编程,所以我决定先不使用AJAX技术来实现。

代码:

from fastapi import FastAPI, Form
from fastapi.responses import Response

import json
from jinja2 import Template

app = FastAPI()


# The page with the table
@app.get('/')  
def index():
    students = get_students()  # Get a list of students
    with open('templates/students.html', 'r', encoding='utf-8') as file:
        html = file.read()
    template = Template(html)  # Creating a template with a table

    # Loading a template
    return Response(template.render(students=students), media_type='text/html')


# Page with forms for adding a new entry
@app.get('/add_student')
def add_student_page():
    with open('templates/add_student.html', 'r', encoding='utf-8') as file:
        html = file.read()

    # Loading a page
    return Response(html, media_type='text/html')


# Processing forms and adding a new entry
@app.post('/add')
def add(name: str = Form(...), surname: str = Form(...), _class: str = Form(...)):
    add_student(name, surname, _class)  # Adding student data
    # ???
python http web jinja2 fastapi
1个回答
5
投票

首先,如果您返回 Jinja2 模板,您应该返回

TemplateResponse
,如 文档中所示。要将用户重定向到特定页面,您可以使用RedirectResponse。由于您通过 POST(而不是 GET)方法执行此操作,如示例所示,因此将引发
405 (Method Not Allowed)
错误。不过,感谢@tiangolo,您可以将响应状态代码更改为
status_code=status.HTTP_303_SEE_OTHER
,问题就会得到解决(请查看这个答案这个答案了解更多详情)。下面给出了一个工作示例。

如果您需要向端点传递额外的 path 和/或 query 参数,请查看 thisthis 答案。

如果您必须执行相同的操作,使用 Fetch API 代替 HTML

<form>
,请查看 这个答案

工作示例

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})

模板/index.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>
© www.soinside.com 2019 - 2024. All rights reserved.