如何在FastAPI中加载index.html

2024-09-30 22:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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')

Tags: fromimport文件夹appindexrequestdisthtml
1条回答
网友
1楼 · 发布于 2024-09-30 22:19:40

替换此项:

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

为此:

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

相关问题 更多 >