python config_error ai_generated true

INFO: 127.0.0.1:xxxxx - "GET /static/style.css HTTP/1.1" 404 Not Found

ID: python/starlette-static-files-404

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-05-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.30+ active — — —

Root Cause

StaticFiles was mounted with a directory that does not exist relative to the process working directory, or the mount path and URL prefix disagree.

generic

中文

StaticFiles 挂载的目录相对于进程工作目录不存在,或挂载路径与 URL 前缀不一致。

Workarounds

  1. 95% success
    from pathlib import Path
    from fastapi.staticfiles import StaticFiles
    BASE = Path(__file__).resolve().parent
    app.mount('/static', StaticFiles(directory=BASE / 'static'), name='static')
  2. 85% success
    assert (BASE / 'static').is_dir(), 'static dir missing'

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Bypasses StaticFiles caching and content-type handling; fragile.

  2. 75% fail

    Shadows API routes registered after the mount.