Jinja2Templates TemplateNotFound and Docker



我的目录结构:

.
|--app
|   |--__init__.py
|   |--main.py
|   |--templates
|        |--index.html
|  
|--Dockerfile
|--requirements.txt

当我尝试在localhost上访问它时,我会得到以下错误:jinja2.exceptions.TemplateNotFound: /code/app/templates/index.html

main.py中,我有以下几行相关代码:

...
app.mount("/static", StaticFiles(directory="/code/app/templates/static"), name="static")
templates = Jinja2Templates(directory="/code/app/templates")
...
@app.get("/")
async def root(request: Request):
return templates.TemplateResponse("/code/app/templates/index.html", {"request": request}

如何允许main看到index.html路径?

DockerfileMy Dockerfile非常接近FastAPI给出的示例。

FROM python:3.10.1
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
ENV PYTHONPATH /code
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

运行命令为docker run -d --name testcon -p 80:80 testimage

您可以尝试登录到容器中查看实际路径,然后使用它。

docker ps -a  # will give you the container id
docker exec -it <container-id> /bin/bash # you are inside the container
pwd # you get the current directory from your Dockerfile it looks like it will be /code

您不需要上面所有的命令来解决这个问题。你可以直接阅读Dockerfile并找出它。以上命令用于确保文件存在。

路径将为templates = Jinja2Templates(directory="/code/app/templates")

以及return templates.TemplateResponse("index.html", {"request": request}

以下线路不需要

app.mount("/static", StaticFiles(directory="/code/app/templates/static"), name="static")

最新更新