Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple flask application that reads its content from a .html file. External style sheet being blocked?

Tags:

python

css

flask

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.

like image 921
Bentley4 Avatar asked Apr 29 '12 14:04

Bentley4


People also ask

How do I connect flask to HTML and CSS?

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.

Can I use flask with HTML?

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?

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.


1 Answers

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"/>
like image 186
Burhan Khalid Avatar answered Sep 19 '22 13:09

Burhan Khalid