Simple flask application that reads its content from a .html file. External style sheet being blocked?
Solution 1
Your code is not serving files using Flask, it is simply reading a file and sending it to the browser - which is why URLs are not working.
You need to render the file from within the method.
First make a templates
folder in the same directory as your .py
file and move your html file into this folder. Create another folder called static
and put your stylesheet in that folder.
You should have
/flaskwp1.py
/templates
webcode.html
/static
webcodestyle.css
Then, adjust your code thusly:
from flask import Flask, render_template
app = Flask('flaskwp1')
# webcode = open('webcode.html').read() - not needed
@app.route('/')
def webprint():
return render_template('webcode.html')
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 3000)
Edit webcode.html
:
<link rel="stylesheet"
type="text/css"
href="/static/webcodestyle.css"/>
Solution 2
You need to create a specific static url and directory.
url_for('static', filename='style.css')
Will enable your app to look for a file called 'style.css' inside a folder called 'static' at the root of your web app module. It will be available to your web app at the url '/static/style.css'
You might want to post the contents of the html file and the python code itself so that we can see what might be going wrong. Sounds like either the url is incorrect or you don't have your web server set up to serve static files from that location.
Bentley4
Profile with mostly old questions where I learned about programming. Thank you SO!
Updated on April 30, 2020Comments
-
Bentley4 about 4 years
I made a very simple flask application that reads its content from a .html file. The application works except for the style. Strangely my inline css code works but not the external style sheet. I've checked the syntax, it should work. Does flask somehow prevent the .css file from being read?
The files in the folder can be viewed here. Those 3 files are all in the same folder.
-
Bentley4 about 12 yearsI posted every file of my webfolder, click "here" in the original post. I tried your suggestion. It didn't change anything. You can see the .py file I adjusted according to your explanation here. If the .css file is in the same folder as the .py and .html file (my original folder setup), then why would it even need the
url_for()
function? -
Bentley4 about 12 yearsI made my folder structure exactly like yours and I adjusted my
flaskwp1.py
andwebcode.html
file like you wrote. It still remains the same. : ( . Thank you for being so elaborate though. -
Bentley4 about 12 yearsThank you, it worked! Is it normal that I always have to restart my browser for the style changes to apply?
-
Burhan Khalid about 12 yearsDepends on your browser's caching; typically you force a request refresh with
CTRL
+F5