我建了一个FastAPI应用,还有一个index、css和js文件,直接打开就能用,但用FastAPI服务时,我无法让css文件显示出来。我试过排除故障,以防问题是CORS的问题,我试过重新排列文件,使其在相同或不同的目录下(并相应地重新指定href路径),但没有任何效果。这是我此时的目录。
working_directory
└── app
|__ index.html
├── style.css
└── main.js
我的应用主页路径是这样设置的。
file_path = "index.html"
@app.get("/")
async def home():
return FileResponse(file_path)
我是否也需要在file_path变量中提供css文件的路径?到目前为止,我尝试过的格式都没有成功,而且FastAPI的错误不像Flask或Django那样有很好的记录。
我的错误是这样的。我的错误是这样的: http:/localhost:8000style.css。 net::ERR_ABORTED 404 (Not Found)
如何让web应用识别我的style.css文件?
你需要实际服务静态文件。下面是一个使用FastAPI的例子。在 "真实世界 "的情况下,你可能会把这些文件留给一个反向代理,比如nginx。
考虑以下结构。
src
app/main.py
static/css/main.css
templates/index.html
主文件.py
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pathlib import Path
app = FastAPI()
app.mount(
"/static",
StaticFiles(directory=Path(__file__).parent.parent.absolute() / "static"),
name="static",
)
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def root(request: Request):
return templates.TemplateResponse(
"index.html", {"request": request}
)
索引.html
...
<link href="{{ url_for('static', path='/css/main.css') }}" rel="stylesheet">
...