【发布时间】:2021-05-24 08:05:11
【问题描述】:
我正在尝试使用以下代码使用 fastapi 重定向到登录页面。我使用 TemplateResponse 重定向到我已经在模板文件夹中创建的 index.html 页面。
文件结构如下
- main.py
- templates -> index.html
- static
main.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})
我尝试这样做,但收到错误"jinja2.exceptions.TemplateNotFound: index.html",当我静态插入一些 HTML 代码时,它可以正常工作,但 TemplateResponse 无法正常工作。即使我尝试在模板文件夹中提供 HTML 文件的完整路径,它也会给出不同的错误。
请指导我如何使这段代码工作,因为我尝试了不同的方式,但无论如何,这段代码给出了一个错误 index.html 找不到模板
【问题讨论】:
-
您的代码在我的机器上运行没有问题(python 3.9.4,fastapi 0.63.0)
标签: python python-3.x templates fastapi