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.
CSS stylesheets are considered static files. There is no interaction with their code, like there is with HTML templates. Therefore, flask has reserved a separate folder where you should put static files such as CSS, Javascript, images or other files. That folder should be created by you and should be named static.
Flask uses the Jinja template library to render templates. In your application, you will use templates to render HTML which will display in the user's browser. In Flask, Jinja is configured to autoescape any data that is rendered in HTML templates.
How do you display Python output on a Flask HTML page? Create a simple HTML page to display text. create a route ”/” and return home. html from the function.
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With