11

I am trying with the below code to redirect to login page using fastapi. I used TemplateResponse to redirect to index.html page which I already created inside the templates folder.

File structure as follows

- 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})

I tried doing it but I am getting an error "jinja2.exceptions.TemplateNotFound: index.html" and when I insert some HTML code statically it's working but TemplateResponse is not working properly. Even when I tried giving an entire path of the HTML file inside the templates folder it's giving a different error.

Please guide me on how to make this code work as I tried with different ways but in any case, this code is giving an error index.html template not found

1
  • Your code is running without issues on my machine (python 3.9.4, fastapi 0.63.0) Commented May 30, 2021 at 17:03

2 Answers 2

9

I just had the same problem when I was doing unit testing and solved it as follows:

from pathlib import Path

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

templates = Jinja2Templates(directory=str(Path(BASE_DIR, 'templates')))
Sign up to request clarification or add additional context in comments.

1 Comment

please use a code block (stackoverflow.com/editing-help)
1

I ran your code with the following and it worked:

uvicorn main:app --reload

I ran into that error this morning when running my own app with supervisord and gunicorn. I found that I had to dynamically set the template directory so that jinja2 knows where the files are:

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

You could use Dependencies in FastAPI to redirect and force a user to login:
https://fastapi.tiangolo.com/tutorial/dependencies/

1 Comment

Why would reload resolve this? I thought reload is for development, if you want your changes to automatically be reloaded. This doesn't feel like the right solution for production

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.