这是一个简单的静态 FastAPI 应用程序。通过此设置,即使根路径预计返回 a FileResponse,custom.html应用程序仍会返回index.html。如何让根路径工作并渲染custom.html?
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
app = FastAPI()
app.mount(
"/",
StaticFiles(directory="static", html=True),
name="static",
)
@app.get("/")
async def index() -> FileResponse:
return FileResponse("custom.html", media_type="html")
Run Code Online (Sandbox Code Playgroud) 当我运行 server.py 文件时出现错误
File "C:\Users\nawin\AppData\Local\Programs\Python\Python38\lib\site-packages\starlette\staticfiles.py", line 57, in __init__
raise RuntimeError(f"Directory '{directory}' does not exist")
RuntimeError: Directory 'app/static' does not exist
Run Code Online (Sandbox Code Playgroud)
服务器.py 文件
app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
app.mount('/static', StaticFiles(directory='app/static'))
Run Code Online (Sandbox Code Playgroud)
python 版本 3.8 操作系统 Windows 10