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/"
@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:-
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 :)
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With