Flask: How to serve static html?
Reducing this to the simplest method that'll work:
- Put static assets into your
static
subfolder. - Leave Flask set to the default, don't give it a
static_url_path
either. - Access static content over the pre-configured
/static/
to verify the file works
If you then still want to reuse a static file, use current_app.send_static_file()
, and do not use leading /
slashes:
from flask import Flask, current_appapp = Flask(__name__)@app.route('/')def hello_world(): return current_app.send_static_file('editor.html')
This looks for the file editor.html
directly inside the static
folder.
This presumes that you saved the above file in a folder that has a static
subfolder with a file editor.html
inside that subfolder.
Some further notes:
static_url_path
changes the URL static files are available at, not the location on the filesystem used to load the data from.render_template()
assumes your file is a Jinja2 template; if it is really just a static file then that is overkill and can lead to errors if there is actual executable syntax in that file that has errors or is missing context.
All the answers are good but what worked well for me is just using the simple function send_file
from Flask. This works well when you just need to send an html file as response when host:port/ApiName will show the output of the file in browser
@app.route('/ApiName')def ApiFunc(): try: #return send_file('relAdmin/login.html') return send_file('some-other-directory-than-root/your-file.extension') except Exception as e: logging.info(e.args[0])```
send_from_directory
and send_file
need to be import
ed from flask
.
Your code sample would work if you do the following:
from flask import Flask, send_from_directoryapp = Flask(__name__, static_url_path='/templates')@app.route('/')def hello_world(): return send_from_directory('templates', 'editor.html')
However, remember if this file loads other files e.g. javascript, css, etc. you would have to define routes for them too.
Also, as far as I understand, this is not the recommended method on production because it's slow.