【问题标题】:Jinja2 template not found找不到 Jinja2 模板
【发布时间】:2021-05-28 14:15:12
【问题描述】:

我正在使用 jinja2 模板和 Fastapi 和 python 来开发 Web 服务器。因此,当网络浏览器发出 get 请求时,我会想要返回一个名为 index.html 的 HTML 页面。但是我看到这个错误,上面写着 raise

TemplateNotFound(template) 
Jinja2.exceptions.TemplateNotFound: index.html 

看看下面的代码:

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates  
  
app = FastAPI()
templates = Jinja2Templates(directory="templates")
    
    
@app.get('/')
    def root(request: Request):
       return templates.TemplateResponse("index.html", {"request": request})

@app.get(‘/home’)
     def home(request:Request, firstname: Optional[Str] = None, lastname: Optional[Str] = None): 
     # process first name last name here 
      processName(firstname,lastname )
    
       return  templates.TemplateResponse("index.html", {"request": request})

def processName(firstname, lastname):
      return “hi “ + firstname + “ “ + lastname

 

HTML 页面显示内部服务器错误。它的网址正在显示

http://localhost:8000/home?firstname=May&lastname=June

【问题讨论】:

  • 嗯,你真的在​​文件templates/index.html中有一个Jinja2模板吗?
  • 是的,我有。启动浏览器并在 index.html 中键入本地 host:8000 时没有问题。仅当浏览器发出查询请求时才会出现问题。
  • 如果可以的话,请帮我解决这个问题stackoverflow.com/questions/67661017/…

标签: python html jinja2 fastapi


【解决方案1】:

对于 fastapi & jinja2 模板,你应该使用绝对路径, 例如:

main.py

from pathfile import Path

# some of codes here....

BASE_PATH = Path(__file__).parent.resolve()
# lets say your template directory is under the root directory
templates = Jinja2Templates(directory=f'{BASE_PATH}/templates')

@app.get('/', response_class=HTMLResponse)
async def homepage(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})

【讨论】:

    【解决方案2】:

    我认为你只需要 3 个空格,一切都会奏效。

    下面的代码中有 3 个锐利,用空格替换它们,你应该会喜欢的。 :D

    @app.get(‘/home’)
     def home(request:Request, firstname: Optional[Str] = None, lastname: Optional[Str] = None): 
     # process first name last name here
     
     ###return  templates.TemplateResponse("index.html", {"request": request})
    

    【讨论】:

    • 为了完整起见,我添加了一些代码。如果函数 processName() 函数被注释掉,返回 HTML 网页就可以了。为什么会这样?
    • 必须在“home”函数之前声明“processName”函数
    • 如果可以的话,请帮我解决这个问题stackoverflow.com/questions/67661017/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 2021-08-12
    • 1970-01-01
    • 2022-01-12
    • 2017-07-16
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多