0
0
Flaskframework~5 mins

Why static file serving matters in Flask

Choose your learning style9 modes available
Introduction

Static file serving lets your web app show images, styles, and scripts to users. Without it, your pages would look plain and not work well.

You want to add pictures or logos to your website.
You need to apply colors and fonts using CSS files.
You want to add interactive features with JavaScript files.
You want to share downloadable files like PDFs or documents.
You want your website to load faster by serving files directly.
Syntax
Flask
from flask import Flask

app = Flask(__name__, static_folder='static')

@app.route('/')
def home():
    return '<img src="/static/logo.png" alt="Logo">'

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

Flask automatically serves files from the static folder.

You link to static files using the /static/filename URL path.

Examples
By default, Flask looks for a folder named static to serve files.
Flask
app = Flask(__name__)
# Default static folder is 'static'
You can change the static folder name by setting static_folder.
Flask
app = Flask(__name__, static_folder='assets')
Use the /static/ path in your HTML to link static files.
Flask
<link rel="stylesheet" href="/static/style.css">
Sample Program

This Flask app serves an HTML page that uses a CSS file and an image from the static folder. Flask automatically handles sending these files when the browser requests them.

Flask
from flask import Flask

app = Flask(__name__)

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

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

Put all your static files like images, CSS, and JavaScript inside the static folder.

Flask serves static files automatically without extra code.

For production, use a web server like Nginx to serve static files faster.

Summary

Static file serving is essential to make web pages look good and work well.

Flask makes it easy by serving files from the static folder automatically.

Use the /static/ URL path to link your static files in HTML.