与 FastAPI 一起使用时无法识别 CSS

Eri*_*rin 6 http-status-code-404 fastapi

我构建了一个 FastAPI 应用程序和一个在直接打开时可以工作的索引、css 和 js 文件,但是在使用 FastAPI 提供服务时我无法显示 css 文件。如果问题是 CORS 问题,我已尝试进行故障排除,我已尝试重新排列文件以使其位于相同或不同的目录中(并相应地重新指定 href 路径),但没有任何效果。这是我此时的目录:

working_directory
??? app
|__ index.html
    ??? style.css
    ??? main.js
Run Code Online (Sandbox Code Playgroud)

像这样设置应用程序主页路线:

file_path = "index.html"

@app.get("/")
async def home():
    return FileResponse(file_path)
Run Code Online (Sandbox Code Playgroud)

我是否还需要在 file_path 变量中提供 css 文件的路径?到目前为止,我尝试过的格式还没有奏效,并且 FastAPI 的错误没有像 Flask 或 Django 那样记录得很好,例如。

我的错误如下: GET http://localhost:8000/style.css net::ERR_ABORTED 404 (Not Found)

我如何让网络应用程序识别我的 style.css 文件?

Hed*_*ide 6

您需要实际提供静态文件。下面是使用 FastAPI 执行此操作的示例。在“真实世界”的场景中,您可能会将这些文件提供给反向代理,例如 nginx。

考虑以下结构;

src
  app/main.py
  static/css/main.css
  templates/index.html
Run Code Online (Sandbox Code Playgroud)

主文件

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}
    )
Run Code Online (Sandbox Code Playgroud)

索引.html

...
<link href="{{ url_for('static', path='/css/main.css') }}" rel="stylesheet">
...
Run Code Online (Sandbox Code Playgroud)