Benjamin Lindley
Benjamin Lindley

Reputation: 103713

How do I generate external CSS dynamically?

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?

Upvotes: 0

Views: 207

Answers (1)

PGHE
PGHE

Reputation: 1962

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')

Upvotes: 3

Related Questions