Flask: How to serve static html?

I am trying to serve a static html file, but it returns error 500 (a copy of editor.html is in the .py and templates directory) This is all I tried:

from flask import Flask app = Flask(__name__, static_url_path='/templates') @app.route('/') def hello_world(): #return 'Hello World1!' #this works correctly! #return render_template('editor.html') #return render_template('/editor.html') #return render_template(url_for('templates', filename='editor.html')) #return app.send_static_file('editor.html') #404 error (Not Found) return send_from_directory('templates', 'editor.html') 

This is the answer:

 Title: 500 Internal Server Srror Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. 
+7
source share
2 answers

Reduce this to the simplest method that will work:

  • Put static assets in the static subfolder.
  • The "Remaining flask" setting is set by default, do not give it static_url_path .
  • Access to static content using pre-configured /static/ to check file operation

If you still want to reuse the static file, use current_app.send_static_file() and don't use the transcoding / :

 from flask import Flask, current_app app = Flask(__name__) @app.route('/') def hello_world(): return current_app.send_static_file('editor.html') 

This looks for the editor.html file directly inside the static folder.

This assumes that you saved the specified file in a folder with a static subtext with the editor.html file inside this subfolder.

Some additional notes:

  • static_url_path changes to static URL files are available, not the location in the file system used to load data.
  • render_template() assumes your file is a Jinja2 template; if it is really just a static file, then this is overkill and can lead to errors if this file has real executable syntax that has errors or is missing context.
+18
source

All the answers are good, but for me the simple send_file function from Flask works well. This works well when you just need to send the html file as an answer, when host: port / ApiName will show the output of the file in the 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])''' 
0
source

Source: https://habr.com/ru/post/971775/


All Articles