Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Flask to serve index.html in a directory

Tags:

python

flask

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

like image 559
Abhirath Mahipal Avatar asked Sep 17 '16 08:09

Abhirath Mahipal


Video Answer


2 Answers

Try this:

@app.route('/results/<path:file>', defaults={'file': 'index.html'})
def serve_results(file):
    # Haven't used the secure way to send files yet
    return send_from_directory(app.config['RESULT_STATIC_PATH'], file)

This is how you pass a default value for that argument. However, I don't agree to this, if you want to serve static content just set a rule in your web server (apache in your case).

like image 71
ipinak Avatar answered Sep 22 '22 18:09

ipinak


I'm using the following single route solution, the "defaults" didn't work for me, as it stopped serving any other file.

Instead of raising the error when the path does not end with a slash, you can also generate a redirect to the path with a slash. Not having this slash but serving the index file with cause problems with relative paths.

@app.route('/<path:path>')
def staticHost(self, path):
    try:
        return flask.send_from_directory(app.config['RESULT_STATIC_PATH'], path)
    except werkzeug.exceptions.NotFound as e:
        if path.endswith("/"):
            return flask.send_from_directory(app.config['RESULT_STATIC_PATH'], path + "index.html")
        raise e
like image 32
Daid Braam Avatar answered Sep 24 '22 18:09

Daid Braam