重定向RedirectResponse
作者:互联网
后台接口
from fastapi import FastAPI, Request, Form from fastapi.templating import Jinja2Templates from fastapi.responses import RedirectResponse import uvicorn app = FastAPI() todos = ["写日记", "看电影", "玩游戏"] template = Jinja2Templates("pages") @app.get("/") async def index(req:Request): return template.TemplateResponse( "index.html", context={"request":req, "todos":todos #定义一个变量传给前端 } #context参数不能少,request键不能更改 ) @app.post("/todo") async def todo(todo=Form(None)): """ 处理接收用户数据 :return:重定向为首页 """ todos.insert(0,todo) return RedirectResponse("/",status_code=302) #前端是post请求,不能直接跳转get请求,会307报错,重定义状态码为302即可 if __name__ == "__main__": uvicorn.run(app="demo:app", host="127.0.0.1", port=8000,debug=True, reload=True)
前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <div> <form action="/todo" method="post"> <input name="todo" placeholder="请添加事项:"> <input type="submit" value="添加"> </form> </div> <h1>待办事项:</h1> {% for todo in todos %} <h1>{{ todo }}</h1> {% endfor %} </body> </html>
标签:__,重定向,app,RedirectResponse,import,todo,todos 来源: https://www.cnblogs.com/zwx901323/p/16324581.html