Abhirath Mahipal Abhirath Mahipal - 1 year ago 138
Python Question

Get Flask to serve index.html in a directory

I have 2 static directories in Flask.

static/




  • css/

  • js/



results/




  • 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/"

@app.route('/results/<path:file>')
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
results
directory.

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

My requirement:-


  • Access any file in the results directory

  • If I send a request for
    localhost:3333/results/1
    I should be served
    index.html



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

Answer Source

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

@app.route('/results/<path:filename>')
def serve_static(filename):
    return send_from_directory("results/", filename)

@app.route('/results/<guid>')
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download