Get Flask to serve index.html in a directory
<p>I have 2 static directories in Flask.</p>

<h3>static/</h3>

<ul>
<li><code>css/</code></li>
<li><code>js/</code></li>
</ul>

<h3>results/</h3>

<ul>
<li><code>1/</code>

<ul>
<li><code>index.html</code></li>
<li><code>details.json</code></li>
</ul></li>
<li><code>2/</code>

<ul>
<li><code>index.html</code></li>
<li><code>details.json</code></li>
</ul></li>
</ul>

<p>I followed along a few other answers and glanced through <a href="http://flask.pocoo.org/docs/0.11/quickstart/#static-files" rel="nofollow">the documentation for serving static files</a>.</p>

<pre><code>app = Flask(__name__)
app.config['RESULT_STATIC_PATH'] = "results/"

@app.route('/results/&lt;path:file&gt;')
def serve_results(file):
    # Haven't used the secure way to send files yet
    return send_from_directory(app.config['RESULT_STATIC_PATH'], file)
</code></pre>

<p>With the following code I can now request for files in the <code>results</code> directory. </p>

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

<p><em>My requirement:-</em></p>

<ul>
<li>Access any file in the results directory</li>
<li>If I send a request for <code>localhost:3333/results/1</code> I should be served <code>index.html</code></li>
</ul>

<p>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 <a href="http://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask">here</a> </p>

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

<p><em>Why did I include details about the static directory?</em><br>
 It is highly possible that I may be doing something wrong. Please let me know. Thanks :)</p>

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

<pre><code>@app.route('/results/&lt;path:filename&gt;')
def serve_static(filename):
    return send_from_directory("results/", filename)

@app.route('/results/&lt;guid&gt;')
def index(guid):
  return send_from_directory("results/" + guid, 'index.html')
</code></pre>

<h2>Other suggestions</h2>

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

<p>@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.</p>

python flask