pip install flask
mkdir flask_static_files
cd flask_static_files
Inside your project folder, create a file named app.py
:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Inside your project folder, create the following structure:
flask_static_files/
│-- static/
│ │-- css/
│ │ ├─ styles.css
│ │-- js/
│ │ ├─ script.js
│ │-- images/
│ │ ├─ flask-logo.png
│-- templates/
│ ├─ index.html
│-- app.py
static/css/styles.css
)body {
background-color: #f4f4f4;
font-family: Arial, sans-serif;
text-align: center;
}
h1 {
color: #333;
}
Step 5: Create a JavaScript File (static/js/script.js
)
document.addEventListener("DOMContentLoaded", function () {
alert("Welcome to Flask with Static Files!");
});
static/images/flask-logo.png
)Download a Flask logo and place it inside the images
folder.
templates/index.html
)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Static Files</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<script src="{{ url_for('static', filename='js/script.js') }}" defer></script>
</head>
<body>
<h1>Flask Static Files Example</h1>
<img src="{{ url_for('static', filename='images/flask-logo.png') }}" alt="Flask Logo" width="200">
</body>
</html>
Run the following command:
python app.py
Open http://127.0.0.1:5000/
in your browser, and you will see:
✅ Styled page with CSS
✅ JavaScript alert message
✅ Flask logo image
In this guide, you have learned how to:
✅ Organize static files in Flask
✅ Link CSS, JavaScript, and images in templates
✅ Use url_for()
to reference static files
Now, you can enhance your Flask applications with styles, interactivity, and images! 🚀