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

Static files 使用FastAPI/Starlette提供静态文件时的相对URL路径,static-files,fastapi,starlette,Static Files,Fastapi,Starlette,我有一个简单的FastAPI应用程序,它在app/main.py中提供一个文件test.html,如下所示: @app.get('/') def index(): return FileResponse('static/test.html') 目录结构如下所示: app/main.py app/static/test.html 我是否可以更改它,使其与修改后的目录结构一起工作,其中app/和static/是同级目录 我尝试了返回FileResponse('../static/test.h

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

@app.get('/')
def index():
  return FileResponse('static/test.html')
目录结构如下所示:

app/main.py
app/static/test.html
我是否可以更改它,使其与修改后的目录结构一起工作,其中
app/
static/
是同级目录


我尝试了
返回FileResponse('../static/test.html')
,但到目前为止还没有成功;如果“static”目录与main.py目录位于同一目录中,则产生的错误为“RuntimeError:路径处的文件../static/test.html不存在”。

尝试:

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

您可以使用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')

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

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

您可以使用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')

是的,这几乎做到了;在计算
父目录路径
时缺少一个
os.pardir
。嘿,这对我来说是可行的,但文件显示为带有扩展名的“下载”。如何强制以正确的名称返回文件?谢谢。是的,这差不多可以了;在计算
父目录路径
时缺少一个
os.pardir
。嘿,这对我来说是可行的,但文件显示为带有扩展名的“下载”。如何强制以正确的名称返回文件?谢谢