【问题标题】:Flask: Resource interpreted as Stylesheet but transferred with MIME type text/htmlFlask:资源解释为样式表,但使用 MIME 类型 text/html 传输
【发布时间】:2016-03-19 13:38:02
【问题描述】:

我使用 Blueprint 的 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的类型没问题)。

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

【问题讨论】:

    标签: javascript python html css flask


    【解决方案1】:

    这和 Flask 有点关系。如果您尝试在没有 Flask 网络服务器的情况下直接访问 HTML,则 html 页面会按预期加载应用的 CSS。

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

    例如

    change => href="{{ url_for('static', filename='stylesheet.css') }}" to href="{{ url_for('static', filename='css/stylesheet.css') }}" OR
    change => href="../static/main.css" to href="../static/css/main.css"
    

    在此更改后,Flask 将按预期加载 CSS,并且 HTML 页面将应用 CSS 而不会发出任何警告。

    【讨论】:

      【解决方案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')
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2012-05-20
          • 2014-11-19
          • 2013-05-04
          • 2011-12-13
          • 2017-10-12
          • 2021-04-25
          • 1970-01-01
          • 2017-02-23
          • 2018-01-23
          相关资源
          最近更新 更多