Abhirath Mahipal Abhirath Mahipal - 1 month ago 18
Python Question

Get Flask to serve index.html in a directory

I have 2 static directories in Flask.


  • css/

  • js/


  • 1/

    • index.html

    • details.json

  • 2/

    • index.html

    • details.json

I followed along a few other answers and glanced through the documentation for serving static files.

app = Flask(__name__)
app.config['RESULT_STATIC_PATH'] = "results/"

def serve_results(file):
# Haven't used the secure way to send files yet
return send_from_directory(app.config['RESULT_STATIC_PATH'], file)

With the following code I can now request for files in the

I'm more familiar with PHP and Apache. Say if a directory has an
file, it is served automatically.

My requirement:-

  • Access any file in the results directory

  • If I send a request for
    I should be served

I can do the same with Flask by adding a route and checking if index.html exists withing the sub directory and then serving it. I found a few more similar pointers here

I currently use two routes to get the functionality. There certainly is a better way.

Why did I include details about the static directory?

It is highly possible that I may be doing something wrong. Please let me know. Thanks :)


I couldn't find a solution which only used one route. I ended up using this.

def serve_static(filename):
    return send_from_directory("results/", filename)

def index(guid):
  return send_from_directory("results/" + guid, 'index.html')

Other suggestions

@ipinak suggested using defaults={'file': 'index.html'} as another parameter. That doesn't solve this problem as it results in some security issue which @ipinak has been kind enough to research about. defaults is a neat option which I'll try using in other places of my application as well.

@dirn suggested in the comments to use Apache/Nginx to serve static files. It would save time as I wouldn't have to implement stuff in Flask. Since static files don't have to passed to the the Python interpreter, we can serve them via another server with hardly any extra work.