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.
Static folder configuration in 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').
app = Flask(__name__)
# Uses default 'static' folder and '/static' URL pathapp = Flask(__name__, static_folder='assets') # Static files are in 'assets' folder but URL path stays '/static'
app = Flask(__name__, static_folder='public', static_url_path='/files') # Static files in 'public' folder, accessed via '/files' URL
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.
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)
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.
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.