Reputation: 11008
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.
Upvotes: 10
Views: 27084
Reputation: 174624
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"/>
Upvotes: 25
Reputation: 25569
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.
Upvotes: 3