【问题标题】:Fastapi : jinja2.exceptions.TemplateNotFound: index.htmlFastapi:jinja2.exceptions.TemplateNotFound:index.html
【发布时间】: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


【解决方案1】:

我使用以下代码运行了您的代码,并且成功了:

uvicorn main:app --reload

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

templates = Jinja2Templates(directory=os.path.abspath(os.path.expanduser('templates)))

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

【讨论】:

    【解决方案2】:

    我刚刚在做单元测试的时候遇到了同样的问题,解决方法如下:

    from pathlib import Path
    
    BASE_DIR = Path(__file__).resolve().parent
    
    templates = Jinja2Templates(directory=str(Path(BASE_DIR, 'templates')))
    

    【讨论】: