5

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

rookie099
  • 2,201
  • 2
  • 26
  • 52
  • Related answers with regard to serving static files in FastAPI can be found [here](https://stackoverflow.com/a/73911598/17865804) and [here](https://stackoverflow.com/a/73113792/17865804). – Chris Jan 15 '23 at 13:09

2 Answers2

2

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')
user368604
  • 166
  • 3
  • Yes, this almost does it; there is an `os.pardir` missing in the calculation of `parent_dir_path`. – rookie099 Jan 21 '20 at 13:37
  • Hey, this works for me but files show up as name "download" with extension. How do I force files to be returned with the correct name? Thanks. – ScipioAfricanus Mar 17 '20 at 18:35
  • exactly the correct answer. this helped me get the correct path as report on the FastAPI github here: https://github.com/tiangolo/fastapi/issues/376 – Zaffer Jun 21 '21 at 21:49
1

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

fquinto
  • 527
  • 7
  • 12