0

I'm not necessarily wanting to do this, I'm just playing around with Flask and I'm curious why this doesn't work. I have the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '''
        <!DOCTYPE html>
        <html>
            <head>
                <link rel="stylesheet" href="styles.css">
            </head>
            <body>
                <h1>This is a heading</h1>
                <p>This is a paragraph.</p>
            </body>
        </html>
    '''

@app.route('/styles.css')
def styles_css():
    return '''
        body {
            background-color: green;
        }
        h1 {
            color: blue;
        }
        p {
            color: red;
        }
    '''

if __name__ == '__main__':
    app.run(debug=True)

When I start the server and navigatge to my.address/ in my browser, I get the HTML page returned by my index function. However, the CSS returned by styles_css is not applied. The server log shows a GET request for /styles.css immediately after the request for /

127.0.0.1 - - [19/Oct/2020 19:54:45] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [19/Oct/2020 19:54:45] "GET /styles.css HTTP/1.1" 200 -

Additionally I can navigate to my.address/styles.css in the browser, and the CSS code is there. So why isn't it being applied to the HTML page?

1 Answer 1

3

You might need to set the media type of your Flask response.

HTML

<link rel="stylesheet" type="text/css"  href="/styles.css">

Flask

from flask import Response
   ...
@app.route('/styles.css')
def styles_css():
    text = '''
        body {
            background-color: green;
        }
        h1 {
            color: blue;
        }
        p {
            color: red;
        }'''

    return Response(text, mimetype='text/css')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.