Reputation: 173
My Flask app which uses Blueprint can’t display the CSS file in Chrome and IE.
Debug information:
Resource interpreted as Stylesheet but transferred with MIME type text/html
My app has these files:
app.py
templates/index.html
static/style.css
And in my app.py
:
app = Blueprint("conf_manager",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/static")
In my index.html
:
<link rel="stylesheet" type="text/css" href="{{ url_for('conf_manager.static', filename='style.css') }}" />
I use Chrome to debug and find that the browser can get the file but the type is text/html
not text/css
(but the JavaScript’s type is okay).
So I want to know why this is happening and how to fix it.
Upvotes: 3
Views: 2520
Reputation: 1
This is somewhat related to Flask. If you try to access the HTML directly without Flask's webserver, the html page loads with applied CSS, as expected.
To be more specific, the actual solution is to create a "css" folder in your "static" folder and then prepend "css/" everywhere in your code where you have a path to a CSS file.
E.g.
Either change this:
href="{{ url_for('static', filename='stylesheet.css') }}"
to
href="{{ url_for('static', filename='css/stylesheet.css') }}"
Or, change this:
href="../static/main.css"
to
href="../static/css/main.css"
After this changes, Flask will load CSS as expected, and the HTML page will have CSS applied to it without any warning.
Upvotes: 0
Reputation: 61
use send_from_directory and setup 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')
Upvotes: 2
Reputation: 173
I figured it out. In the main app someone added response.headers["Content-Type"] = 'text/html; CharSet=UTF-8'
, so IE can’t read the CSS.
And my code in app.py
app = Blueprint("conf_manager",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/static")
should be changed to:
app = Blueprint("conf_manager",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/conf_manager/static")
Upvotes: 2