Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

python - Flask: How to serve static html?

I am trying to serve a static html file, but returns a 500 error (a copy of editor.html is on .py and templates directory) This is all I have 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 response:

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reducing this to the simplest method that'll work:

  1. Put static assets into your static subfolder.
  2. Leave Flask set to the default, don't give it a static_url_path either.
  3. 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_app
app = 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...