加载index.html的最小fastapi示例

do-*_*-me 35 fastapi

在我的项目文件夹中,我有一个基本index.html文件加上静态文件(js、css)以及我的main.py

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

app = FastAPI()

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

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

我怎样才能让fastapi在这里工作?我只想index.html在本地主机上提供我的静态文件。没有staticortemplates文件夹有问题吗?

do-*_*-me 66

方案一:静态文件挂载

这比预期的要容易。只需将所有静态文件放入项目目录中的文件夹index.htmlstatic并挂载静态文件即可。

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")
Run Code Online (Sandbox Code Playgroud)

就是这样。我的index.html现在可以在http://localhost:8000/static/index.html.

如果它应该可以在http://localhost:8000/没有/static.html结尾的情况下访问,则需要更改两件事。首先需要安装它,/并且安装时/static必须设置 HTML 标志。true所以只需使用这一行即可:

app.mount("/", StaticFiles(directory="static",html = True), name="static")
Run Code Online (Sandbox Code Playgroud)

(感谢这个答案

index.html现在可以在下面找到http://localhost:8000/


选项 2:仅提供服务index.html

由于 fastapi 基于 starlette,因此一个简单的FileResponse 任务就可以完成。

from starlette.responses import FileResponse 

@app.get("/")
async def read_index():
    return FileResponse('index.html')
Run Code Online (Sandbox Code Playgroud)

在这里找到的。

  • 请注意,定义端点(以及独立应用程序,例如“StaticFiles”)的顺序**重要**。请查看[此答案](/sf/answers/5117965471/)和[此答案](/sf/answers/5214906441/)了解更多详细信息。 (3认同)
  • 如果我说你可以从“fastapi.responses”导入“FileResponse”会有帮助吗?它只是一个类,fastapi 的渲染机制将其视为文件 _index.html_ 的内容。 (2认同)

小智 13

对我有用的最好和最简单的解决方案:

\n
from fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\napi_app = FastAPI(title="api app")\n\n@api_app.post("/set_influencers_to_follow")\nasync def set_influencers_to_follow(request):\n    return {}\n\napp = FastAPI(title="main app")\n\napp.mount("/api", api_app)\napp.mount("/", StaticFiles(directory="ui", html=True), name="ui")\n
Run Code Online (Sandbox Code Playgroud)\n

如果项目结构如下:

\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 ui\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 index.html\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 style.css\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 script.js\n
Run Code Online (Sandbox Code Playgroud)\n


归档时间:

查看次数:

32009 次

最近记录:

3 年,4 月 前