Good way to manage static files and templates with fastapi?

Question:

Is there some good way to manage static files with fastapi ? I currently am trying to make a bigger application in fastapi and have to create multiple such folders for each router :/.

Asked By: mini5183

||

Answers:

I also had the same issue some time ago…
My file structure is like

main.py # The main file which contains the fastapi instance )
src
-- folders in here with `__init__.py` in src folder and each folder src contains


# It would be like
main.py
src
  - __init__.py
  - folder1
    - __init__.py
    - folder1.py

Then in the main.py file

from src.folder1 import folder1 as folder1_main
...
# In the end of code i add

app.include_router(folder1_main.router)

So, for static files just create a folder named like staticserve in src folder and in there put something like this ( not to add as router though )

def templateit(appobj):
    dir_path = os.path.dirname(os.path.realpath(__file__))
    appobj.mount("/static", StaticFiles(directory=f"{dir_path}/static"), name="static")
    templates = Jinja2Templates(directory=f"{dir_path}/templates")
    return templates

Now when using templates in main.py or in some other folder in src, just import this func from there and

    return cur.TemplateResponse(
        "index.html",
        {
            "request": request,
        }, status_code=200
        )

Note : make a folder named static and templates in staticserve dir…

Also, sometimes it gives issue with endpoints like /a/b , works fine with /a though..

Answered By: Ayush Sehrawat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.