rookie099
rookie099

Reputation: 2617

relative URL paths when serving static files with FastAPI/Starlette

I have a simple FastAPI application that serves a file test.html in app/main.py like so:

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

The directory structure is like so:

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

Can I change this do that it works with a modified directory structure where app/ and static/ are siblings?

I have tried return FileResponse('../static/test.html') but that has not worked so far; the resulting error is "RuntimeError: File at path ../static/test.html does not exist."

Upvotes: 5

Views: 13416

Answers (2)

fquinto
fquinto

Reputation: 597

My proposal: then you have static mounted.

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")

or use without that:

return FileResponse(st_abs_file_path + 'test.html')

More explained here: https://stackoverflow.com/a/69401919/5824889

Upvotes: 1

user368604
user368604

Reputation: 166

If your 'static' dir is in the same dir as your main.py
Try:

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

Looks like you were looking in the folder above.

you could could os.path to get the parent dir

import os 
parent_dir_path = os.path.dirname(os.path.realpath(__file__))

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

Upvotes: 2

Related Questions