0
0
Flaskframework~5 mins

Static folder configuration in Flask

Choose your learning style9 modes available
Introduction

Static folder configuration tells Flask where to find files like images, CSS, and JavaScript that do not change. This helps your web app show styles and pictures correctly.

You want to add a logo or image to your website.
You need to include CSS files to style your pages.
You want to add JavaScript files for interactive features.
You want to organize your static files in a custom folder.
You want Flask to serve static files from a different folder than the default.
Syntax
Flask
app = Flask(__name__, static_folder='folder_name', static_url_path='/url_path')

static_folder sets the folder where static files live (default is 'static').

static_url_path sets the URL path to access static files (default is '/static').

Examples
This uses the default settings. Put your files in a folder named 'static'.
Flask
app = Flask(__name__)
# Uses default 'static' folder and '/static' URL path
Change the folder name to 'assets' but keep the URL path as '/static'.
Flask
app = Flask(__name__, static_folder='assets')
# Static files are in 'assets' folder but URL path stays '/static'
Change both the folder and the URL path for static files.
Flask
app = Flask(__name__, static_folder='public', static_url_path='/files')
# Static files in 'public' folder, accessed via '/files' URL
Sample Program

This Flask app uses a custom static folder named 'my_static' and serves static files at '/staticfiles'. The HTML page links a CSS file and an image from this folder.

Flask
from flask import Flask

app = Flask(__name__, static_folder='my_static', static_url_path='/staticfiles')

@app.route('/')
def home():
    return '''
    <html>
      <head>
        <link rel="stylesheet" href="/staticfiles/style.css">
      </head>
      <body>
        <h1>Welcome!</h1>
        <img src="/staticfiles/logo.png" alt="Logo">
      </body>
    </html>
    '''

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

Make sure the folder you set for static_folder exists and contains your static files.

The static_url_path is the URL prefix you use in your HTML to access static files.

If you don't set these parameters, Flask uses 'static' folder and '/static' URL by default.

Summary

Static folder configuration tells Flask where to find and how to serve static files.

You can customize the folder name and URL path for static files.

This helps organize your files and control how users access images, CSS, and JavaScript.