小编典典

使用 fastapi 管理静态文件和模板的好方法?

all

有没有一些用 fastapi 管理静态文件的好方法?我目前正在尝试在 fastapi 中创建一个更大的应用程序,并且必须为每个路由器创建多个这样的文件夹:/。


阅读 65

收藏
2022-08-15

共1个答案

小编典典

前段时间我也有同样的问题......我的文件结构就像

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

然后在 main.py 文件中

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

app.include_router(folder1_main.router)

因此,对于静态文件,只需在 src 文件夹中创建一个名为 staticserve 的文件夹,然后在其中放置类似的内容(尽管不要添加为路由器)

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

现在,当在 main.py 或 src 的其他文件夹中使用模板时,只需从那里导入这个函数并

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

注意:在 staticserve 目录中创建一个名为 static 和模板的文件夹…

此外,有时它会给端点等问题带来问题/a/b,但可以正常工作/a..

2022-08-15