Relative Template Directories Resolve Against the Working Directory, Not the Source File
Jinja2Templates(directory="templates") looks for templates/ in the process's current working directory, not next to the Python file that wrote it. The app works when started from its own folder and fails with TemplateNotFound when a test runner, a script or a container starts it from somewhere else.
Why the Path Moves
Starlette hands the directory to Jinja2's FileSystemLoader, and Python resolves any relative path against the working directory of the process. The same code therefore finds different folders depending on where the command ran: uvicorn main:app from the app folder works, pytest from the repository root looks for <root>/templates/.
Anchor the Path to the Source File
from pathlib import Path
from fastapi.templating import Jinja2Templates
BASE_DIR = Path(__file__).resolve().parent
templates = Jinja2Templates(directory=BASE_DIR / "templates")
__file__ is the module's own path, so BASE_DIR is the same whatever the working directory. Define it once (in a settings or config module) and build every resource path from it.
References
- FastAPI MOC - hub for FastAPI notes.
- FastAPI documentation: Templates -
Jinja2Templatessetup. - Jinja2 documentation: FileSystemLoader - relative paths resolve against the current working directory.
- Python documentation: pathlib -
Path.resolve()and/for joining paths.
Review cards
Flashcard `uvicorn main:app` finds the templates, but `pytest` from the repository root raises `TemplateNotFound`. Why?
directory="templates" is relative, and Python resolves relative paths against the process's working directory, not the source file. From the root, it looks for <root>/templates/.
Quiz Which template directory still works when the app is started from another working directory?
- Jinja2Templates(directory="templates")
- Jinja2Templates(directory=Path(file).resolve().parent / "templates")
- Jinja2Templates(directory=os.getcwd() + "/templates")
- Jinja2Templates(directory="../../templates")
Only a path anchored to the source file's location is independent of the working directory. The others all resolve against the CWD.