Flask:如何提供静态 html? [英] Flask: How to serve static html?

查看:43
本文介绍了Flask:如何提供静态 html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提供静态 html 文件,但返回 500 错误(editor.html 的副本位于 .py 和模板目录中)这就是我所尝试的:

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

这是回复:

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.

推荐答案

将其简化为可行的最简单方法:

Reducing this to the simplest method that'll work:

  1. 将静态资源放入您的 static 子文件夹中.
  2. 将 Flask 设置为默认值,也不要给它一个 static_url_path.
  3. 通过预先配置的/static/访问静态内容以验证文件是否有效
  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

如果您仍然想重用静态文件,请使用 current_app.send_static_file(),并且不要使用前导 / 斜杠:

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

这会在 static 文件夹中查找文件 editor.html 直接.

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

这假定您将上述文件保存在一个文件夹中,该文件夹具有一个 static 子文件夹,该子文件夹内有一个文件 editor.html.

This presumes that you saved the above file in a folder that has a static subfolder with a file editor.html inside that subfolder.

一些进一步的说明:

  • static_url_path 更改了 URL 静态文件可用的位置,而不是用于从中加载数据的文件系统上的位置.
  • render_template() 假设您的文件是 Jinja2 模板;如果它真的只是一个静态文件,那么这就是矫枉过正,并且如果该文件中的实际可执行语法存在错误或缺少上下文,则可能会导致错误.
  • 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.

这篇关于Flask:如何提供静态 html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆