Welcome back to CodeYourCraft! Today, we're going to dive into an exciting topic: working with static files in Flask. This includes CSS, JavaScript, and images. Let's get started!
Static files are files that don't change during a web application's runtime, such as HTML, CSS, JavaScript, images, and fonts. They're essential for enhancing the visual appeal and interactivity of our web applications.
Before we can serve static files, we need to tell Flask where to find them. Let's create a new Flask project and set up the necessary folder structure:
my_flask_app/
|- app.py
|- static/
|- css/
|- style.css
|- js/
|- script.js
|- images/
|- logo.png
Make sure you have flask installed in your virtual environment. If not, install it using pip install flask.
Now, let's modify our app.py to serve the static files:
from flask import Flask, send_from_directory
app = Flask(__name__)
app.config['STATIC_URL_PATH'] = '/static/'
@app.route('/')
def home():
return send_from_directory('static', 'index.html')
@app.route('/static/<path:path>')
def serve_static(path):
return send_from_directory('static', path)
if __name__ == '__main__':
app.run(debug=True)Let's break down the code above:
STATIC_URL_PATH is set to '/static/'. This tells Flask to look for static files under the static folder in the root directory of our project.home() function serves our project's index.html file (which we'll create next).serve_static() function serves any static file requested by the user.Now, let's create an index.html file inside the static/css folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Flask App</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1>Welcome to My Flask App!</h1>
<script src="/static/js/script.js"></script>
</body>
</html>This HTML file includes a link to our CSS and JavaScript files, as well as a simple header.
Now, let's style our app by creating a style.css file inside the static/css folder:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: #333;
}Save the file, and refresh your browser to see the changes.
Next, let's add some interactivity to our app by creating a script.js file inside the static/js folder:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('h1').addEventListener('click', function() {
alert('You clicked the heading!');
});
});This JavaScript code listens for a click event on the h1 element and shows an alert when the heading is clicked.
Now that we have our static files set up and linked correctly, let's serve our app:
$ python app.pyVisit http://127.0.0.1:5000/ in your browser to see your finished Flask app with CSS, JavaScript, and an interactive heading!
What does Flask use to serve static files like CSS, JavaScript, and images?
That's it for today! You now have a basic understanding of serving static files in Flask. In the next lesson, we'll dive deeper into Flask templates and form handling. Happy coding! 💻🌟