0
0
Flaskframework~30 mins

Why static file serving matters in Flask - See It in Action

Choose your learning style9 modes available
Why static file serving matters
📖 Scenario: You are building a simple Flask web app that needs to show a logo image and a CSS style to make the page look nice. These files are called static files because they do not change dynamically. Serving static files correctly is important so your users see the images and styles properly.
🎯 Goal: Create a Flask app that serves a static image and a CSS file. You will set up the static folder, configure the app to use it, and link the static files in your HTML template.
📋 What You'll Learn
Create a Flask app with a static folder named static
Add an image file named logo.png inside the static folder
Add a CSS file named style.css inside the static folder
Serve the static files correctly in the Flask app
Link the static files in the HTML template using Flask's url_for function
💡 Why This Matters
🌍 Real World
Web apps often need to serve images, styles, and scripts to users. Knowing how to serve static files ensures your app looks good and works well.
💼 Career
Web developers must understand static file serving to build professional websites and apps that load resources efficiently and correctly.
Progress0 / 4 steps
1
Set up the Flask app and static folder
Create a Flask app in a file named app.py with the line app = Flask(__name__). Also, create a folder named static in the same directory. Inside the static folder, place an image file named logo.png.
Flask
Need a hint?

Remember, Flask automatically looks for a folder named static for static files.

2
Add a CSS file in the static folder
Inside the static folder, create a CSS file named style.css with some basic style, for example, body { background-color: lightblue; }.
Flask
Need a hint?

The CSS file should be inside the static folder, not in the main app folder.

3
Create a route and HTML template linking static files
In app.py, create a route for / that returns an HTML string. Use Flask's url_for('static', filename='logo.png') to link the image and url_for('static', filename='style.css') to link the CSS file inside the HTML.
Flask
Need a hint?

Use url_for('static', filename='...') inside the HTML string to link static files.

4
Run the Flask app with debug mode
Add the code to run the Flask app with app.run(debug=True) inside the if __name__ == '__main__': block at the end of app.py.
Flask
Need a hint?

This code lets you run the Flask app and see changes immediately because debug mode is on.