在我的项目文件夹中,我有一个基本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
在本地主机上提供我的静态文件。没有static
ortemplates
文件夹有问题吗?
do-*_*-me 66
这比预期的要容易。只需将所有静态文件放入项目目录中的文件夹index.html
中static
并挂载静态文件即可。
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/
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)
在这里找到的。
小智 13
对我有用的最好和最简单的解决方案:
\nfrom 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 次 |
最近记录: |