Issue
I have a Flask application that uses pypandoc to generate and serve static HTML from markdown. Everything works fine, but the css file is served as text/html
instead of text/css
so it is not interpreted.
I get the following error in Firefox/Chromium:
The stylesheet http://127.0.0.1:5000/static/notes.css was not loaded because its mime type "text/html" is not "text/css" .
In Flask app (extracted with pypandoc command)
...
css = url_for('static', filename='notes.css')
vcss='--css='+css
pdoc_args = ['--template=templates/notes.html',
VCSS
]
output = ppandoc.convert_text(mdblop, 'html', format='markdown', extra_args=pdoc_args, outputfile=filename)
Using open(filename) as fp:
htmlpage = fp.read()
return html page
...
In the Pandoc template notes.html
$for(css)$
$endfor$
I added type="text/css"
in an attempt to force the type, but it didn’t help/change.
Css file notes.css
is a standard css file.
Final HTML served by Flask:
Flask doesn’t seem to properly recognize this static file as a text/css
type.
Added a legacy function to serve static files with interestingly contradictory MIME type tests.
@app.get("/static/")
def route_static (file name):
filename = os.path.join('static', filename)
print(mimetypes.guess_type('/static/notes.css')) # returns "('text/css', None)"
print(mimetypes.read_mime_types('/static/notes.css')) # returns "none"
Using open(filename) as fp:
staticfile = fp.read()
return static files
Solution
I found the solution looking at the package flask_FlatPages (which is not needed in my case, but it documents a way to force the mimetypes of the returned element.
So my function for serving css as text/css
:
@app.get("/static/notes.css")
def static_notescss():
filename = os.path.join('static', 'notes.css')
with open(filename) as fp:
staticfile = fp.read()
return staticfile, 200, {'Content-Type': 'text/css'}
This final element makes it right : {'Content-Type': 'text/css'}
Answered By – laconis
Answer Checked By – Katrina (Easybugfix Volunteer)