fastapi挂载静态文件夹,本地运营正常,上传服务器后,RuntimeError: Directory 'static' does not exist

本地运行正常,上传服务器错误代码

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"))


@app.get("/")
def index():
    return FileResponse("static/index.html")


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app)

运行结果 RuntimeError: Directory 'static' does not exist

修改后代码

import os.path

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

app = FastAPI()

static_file_abspath = os.path.join(os.path.dirname(__file__), "static")

app.mount("/static", StaticFiles(directory=static_file_abspath), name="static")


@app.get("/")
def index():
    return FileResponse(f"{static_file_abspath}/index.html")


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app)

问题主要出现在路径上面,不这样写的话,在服务器上就直接写绝对地址。代码也能正常运行!

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐