Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Good way to manage static files and templates with fastapi?

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 :/.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading