Flask Static Files Using Static Files


Example

Web applications often require static files like CSS or JavaScript files. To use static files in a Flask application, create a folder called static in your package or next to your module and it will be available at /static on the application.

An example project structure for using templates is as follows:

MyApplication/
    /static/
        /style.css
        /script.js
    /templates/
        /index.html
    /app.py

app.py is a basic example of Flask with template rendering.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

To use the static CSS and JavaScript file in the template index.html, we need to use the special 'static' endpoint name:

{{url_for('static', filename = 'style.css')}}

So, index.html may contain:

<html>
    <head>
        <title>Static File</title>
        <link href="{{url_for('static', filename = 'style.css')}}" rel="stylesheet">
        <script src="{{url_for('static', filename = 'script.js')}}"></script>
    </head>
    <body>
        <h3>Hello World!</h3>
    </body>
</html>

After running app.py we will see the webpage in http://localhost:5000/.