Fastapi:jinja2.exceptions.TemplateNotFound:index.html

Sag*_*a S 9 python templates python-3.x fastapi

我正在尝试使用下面的代码使用 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

小智 7

我在进行单元测试时遇到了同样的问题,并解决如下:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent

templates = Jinja2Templates(directory=str(Path(BASE_DIR, 'templates')))
Run Code Online (Sandbox Code Playgroud)


小智 1

我使用以下代码运行了您的代码并且它有效:

uvicorn main:app --reload
Run Code Online (Sandbox Code Playgroud)

今天早上我在使用supervisord和gunicorn运行我自己的应用程序时遇到了这个错误。我发现我必须动态设置模板目录,以便 jinja2 知道文件在哪里:

templates = Jinja2Templates(directory=os.path.abspath(os.path.expanduser('templates')))
Run Code Online (Sandbox Code Playgroud)

您可以使用 FastAPI 中的依赖项来重定向并强制用户登录: https:
//fastapi.tiangolo.com/tutorial/dependency/