【问题标题】:relative URL paths when serving static files with FastAPI/Starlette使用 FastAPI/Starlette 提供静态文件时的相对 URL 路径
【发布时间】:2020-05-04 23:47:39
【问题描述】:

我有一个简单的 FastAPI 应用程序,它在 app/main.py 中提供文件 test.html,如下所示:

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

目录结构是这样的:

app/main.py
app/static/test.html

我可以更改此操作以使其适用于 app/ 和 static/ 是兄弟姐妹的修改目录结构吗?

我已经尝试过return FileResponse('../static/test.html'),但到目前为止还没有奏效;产生的错误是“RuntimeError: 路径 ../static/test.html 中的文件不存在。”

【问题讨论】:

    标签: static-files fastapi starlette


    【解决方案1】:

    如果您的“静态”目录与 main.py 位于同一目录中
    试试:

    return FileResponse('./static/test.txt')
    

    看起来您正在查看上面的文件夹。

    你可以通过 os.path 来获取父目录

    import os 
    parent_dir_path = os.path.dirname(os.path.realpath(__file__))
    
    @app.get('/')
    def index():
      return FileResponse(parent_dir_path + '/static/test.html')
    

    【讨论】:

    • 是的,这几乎可以做到; parent_dir_path 的计算中缺少一个 os.pardir。
    • 嘿,这对我有用,但文件显示为带有扩展名的“下载”名称。如何强制以正确的名称返回文件?谢谢。
    • 完全正确的答案。这帮助我在 FastAPI github 上获得了正确的路径:github.com/tiangolo/fastapi/issues/376
    【解决方案2】:

    我的建议:那么你已经 static 挂载了。

    import os
    script_dir = os.path.dirname(__file__)
    st_abs_file_path = os.path.join(script_dir, "static/")
    app.mount("/static", StaticFiles(directory=st_abs_file_path), name="static")
    

    或不使用:

    return FileResponse(st_abs_file_path + 'test.html')
    

    更多解释在这里:https://stackoverflow.com/a/69401919/5824889

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      相关资源
      最近更新 更多