我有一個包含學生表的頁面。我添加了一個按鈕,允許您向表中添加新行。為此,我將用戶重定向到帶有輸入表單的頁面。
問題是在提交完成的表單后,用戶會轉到一個新的空白頁面。如何以完整的表格傳輸資料并將用戶重定向回表格?
我剛開始學習 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
# ???
uj5u.com熱心網友回復:
首先,在您回傳 jinja2 模板的情況下,您應該回傳一個 TemplateResponse,如檔案中所示。要將用戶重定向到特定頁面,您可以使用RedirectResponse。由于您通過 POST(而不是 GET)方法(如示例中所示)執行此操作,因此將引發405(不允許的方法)錯誤。但是,感謝@tiangolo,您可以將回應狀態代碼更改為status_code=status.HTTP_303_SEE_OTHER,問題將得到解決。下面是一個作業示例。如果您將來需要將路徑和/或查詢引數傳遞給您的端點,請查看此或此答案 也是。
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})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411186.html
標籤:
