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

Flask: Resource interpreted as Stylesheet but transferred with MIME type text/html

本文关键字:MIME 类型 text 传输 html 资源 解释 样式 Flask      更新时间:2023-09-26

使用Blueprint的My Flask应用程序无法在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的类型还可以)。

所以我想知道为什么会发生这种情况,以及如何修复它。

我想明白了。在主应用程序中,有人添加了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")

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

这在某种程度上与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。