I tried to follow the tutoria to form a bigger application
https://fastapi.tiangolo.com/tutorial/bigger-applications/
the project structure is like :
.
โโโ app
โ โโโ __init__.py
โ โโโ main.py
โ โโโ model.py
โ โโโ countries.gz
โ โโโ routers
โ โโโ __init__.py
โ โโโ items.py
โ โโโ users.py
โ โโโ templates
โ โโโ layout.html
โ โโโ home.html
โ โโโ world.html
main.py:
from fastapi import FastAPI, Request, APIRouter
from .routers import us_router, world_router
app = FastAPI()
# should I add some config here?
app.include_router(us_router.router)
app.include_router(world_router.wrouter)
in the /routers/items.py
from fastapi.templating import Jinja2Templates
wrouter = APIRouter()
templates = Jinja2Templates(directory='templates')
# if the router.py is in the same level of templates directory, this will work.
# should I change something here? I tried '../templates', not work.
@wrouter.get("/world", response_class=HTMLResponse)
async def world(request: Request):
flist = fig.fig_world('total_cases')
return templates.TemplateResponse('world.html', {'request': request,
'line_latest': flist[0],
}
)
The problem:
cannot find the world.html, which is in templates directory.
If I use a absolute directory 'home/eric/fastapi/app/templates', it will work.
model.py:
import pandas as pd
df = pd.read_pickle('countries.gz')
# this is very confusing, I tried './countries.gz', not work
......
Problem:
cannot find the 'countries.gz' in the same directory. use absolute directory will work.
expected answer:
As a beginner, I am confused on the logic. I would like to know what is the best practice to handle the directories in the fastapi project?
Thanks a lot.
can you put here your executes command?
do you run the command inside app directory or outside of that?
I execute just outside the app directory: uvicorn app.main:app --reload
OH!
change like this will work:
templates = Jinja2Templates(directory='./app/templates')
Thank you so much, the project root dir is the excute directory, NOT the main.py.directory.
My follow up question is:
Will it be more reasonable if I set the main.py directory as root? where should I config, If I want to do this,
You probably want to do something like this:
from os.path import dirname, join
current_dir = dirname(__file__) # this will be the location of the current .py file
templates = join(current_dir, 'templates')
Thanks!
wonderful!