我正在尝试使用下面的代码使用 fastapi 重定向到登录页面。我使用 TemplateResponse 重定向到我已经在 templates 文件夹中创建的 index.html 页面。
文件结构如下
- main.py
- templates -> index.html
- static
Run Code Online (Sandbox Code Playgroud)
主要.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def login_page(request :Request):
return templates.TemplateResponse("index.html", {"request":request})
Run Code Online (Sandbox Code Playgroud)
我尝试这样做,但出现错误"jinja2.exceptions.TemplateNotFound: index.html",当我静态插入一些 HTML 代码时,它可以工作,但 TemplateResponse 无法正常工作。即使当我尝试在模板文件夹内提供 HTML 文件的完整路径时,它也会给出不同的错误。
请指导我如何使此代码工作,因为我尝试了不同的方法,但无论如何,此代码都会给出错误index.html template not found