在我的项目文件夹中,我有一个基本的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})
如何让fastapi在这里工作?我只是想我的index.html
和静态文件服务于本地主机。没有static
或templates
文件夹是否有问题?
选项1:静态文件挂载
这比预期的要容易。只需要将包括index.html
在内的所有静态文件放入项目目录下的static
文件夹,并挂载静态文件。
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
就是这样。我的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")
(Thanks to this answer)
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')
在这里找到。
最适合我的最简单的解决方案:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
api_app = FastAPI(title="api app")
@api_app.post("/set_influencers_to_follow")
async def set_influencers_to_follow(request):
return {}
app = FastAPI(title="main app")
app.mount("/api", api_app)
app.mount("/", StaticFiles(directory="ui", html=True), name="ui")
如果项目结构如下:
├── main.py
├── ui
│ ├── index.html
│ ├── style.css
│ ├── script.js