使用 FastAPI/Starlette 提供静态文件时的相对 URL 路径

roo*_*099 5 static-files starlette fastapi

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

@app.get('/')
def index():
  return FileResponse('static/test.html')
Run Code Online (Sandbox Code Playgroud)

目录结构是这样的:

app/main.py
app/static/test.html
Run Code Online (Sandbox Code Playgroud)

我可以更改它吗?它可以使用修改后的目录结构(其中app/static/是同级目录)吗?

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

use*_*604 2

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

return FileResponse('./static/test.txt')
Run Code Online (Sandbox Code Playgroud)

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

你可以 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')
Run Code Online (Sandbox Code Playgroud)