Flask:资源被解释为样式表,但传输的MIME类型为text/html。

3

我的 Flask 应用使用了 Blueprint,但在 Chrome 和 IE 中无法显示 CSS 文件。

调试信息如下:

资源被解释为样式表,但传输的 MIME 类型为 text/html

我的应用有以下文件:

app.py
templates/index.html
static/style.css

在我的app.py文件中:

app = Blueprint("conf_manager",
  __name__,
  template_folder="templates",
  static_folder="static",
  static_url_path="/static")

在我的index.html中:
<link rel="stylesheet" type="text/css" href="{{ url_for('conf_manager.static', filename='style.css') }}" />

我使用Chrome进行调试,发现浏览器能够获取文件,但类型是text/html而不是text/css(但JavaScript的类型没问题)。

因此,我想知道为什么会出现这种情况以及如何解决它。

3个回答

2
我想明白了。在主应用程序中,有人添加了response.headers["Content-Type"] = 'text/html; CharSet=UTF-8',所以IE无法读取CSS。
而我的代码在app.py中。
app = Blueprint("conf_manager",
        __name__,
        template_folder="templates",
        static_folder="static",
        static_url_path="/static")

应该更改为:

app = Blueprint("conf_manager",
        __name__,
        template_folder="templates",
        static_folder="static",
        static_url_path="/conf_manager/static")

2

使用send_from_directory并设置mimetype:

from flask import send_from_directory

scriptPath = os.path.dirname(os.path.realpath(__file__))
os.chdir(scriptPath) 

template_folder = os.path.join(os.getcwd(),'templates')
static_folder = os.path.join(os.getcwd(),'static')
app = Flask(__name__, template_folder=template_folder,static_folder=static_folder)

@app.route('/css/<path:path>')
def send_css(path):
    return send_from_directory('css', path,mimetype='text/css')

0

这与Flask有些相关。如果您尝试在没有Flask Web服务器的情况下直接访问HTML,则HTML页面将加载已应用的CSS,如预期。

更具体地说,实际解决方案是在“静态”文件夹中创建一个“css”文件夹,然后在代码中任何路径到CSS文件的位置处添加“css /”前缀。

例如:

要么改变这个:

href="{{ url_for('static', filename='stylesheet.css') }}" 

href="{{ url_for('static', filename='css/stylesheet.css') }}" 

或者,更改这个:

href="../static/main.css"

href="../static/css/main.css"

在这些更改之后,Flask将按预期加载CSS,HTML页面将应用CSS而不会出现任何警告。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接