【问题标题】:CSS not recognized when served with FastAPI使用 FastAPI 服务时无法识别 CSS
【发布时间】:2020-08-21 18:55:29
【问题描述】:

我构建了一个 FastAPI 应用程序和一个直接打开时可以使用的索引、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 那样详细记录。

我的错误如下所示: GET http://localhost:8000/style.css net::ERR_ABORTED 404(未找到)

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

【问题讨论】:

    标签: python http-status-code-404 fastapi


    【解决方案1】:

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

    考虑以下结构;

    src
      app/main.py
      static/css/main.css
      templates/index.html
    

    main.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}
        )
    

    index.html

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

    【讨论】:

    • 非常感谢!这很有帮助!:)
    猜你喜欢
    • 2023-03-24
    • 2015-12-12
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多