如何在 FastAPI 中加载 index.html

How to load index.html in FastAPI

我在 Vue 中构建了我的应用程序,在 Python 中使用 FastAPI 构建了我的后端。在我完成 npm run build 之后,我将 dist 文件夹复制到 templates 文件夹中。我想加载 index.html,但出现错误 error_aborted 404 (not found)static 文件夹位于 templates 文件夹内。为什么会出现此错误?

from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="templates"))

@app.get("/")
def serve_home(request: Request):
    return templates.TemplateResponse("index.html", context= {"request": request})

我也试过下面的代码,把dist文件夹放在static文件夹里,没有templates文件夹。

@app.get("/")
async def index():
    return FileResponse('static/index.html', media_type='text/html')

替换为:

app.mount("/static", StaticFiles(directory="templates"))

有了这个:

app.mount("/", StaticFiles(directory="templates"))