Flask Static Files: A Comprehensive Guide with Examples

Flask Static Files Guide with Examples

 

Flask, a lightweight and flexible web framework for Python, is an excellent choice for building web applications. One of its core features is the ability to serve static files such as CSS, JavaScript, and images, which are essential for creating a rich and interactive user experience. In this blog post, we'll explore how to manage Flask static files, complete with practical examples.

 

 

Flask Static Files with Examples

 

Understanding Static Files in Flask 

 

Static files are resources that don’t change on the server-side and are sent directly to the client's browser. They include:

  • CSS files for styling
  • JavaScript files for interactivity
  • Images and other multimedia files


Flask makes it easy to handle these files with a predefined folder named `static`. By default, Flask will serve any file in the `static` folder at the `/static` URL path.

 

Read also: Flask Tutorial: Templates 

 

 

Setting Up Your Flask Application



First, ensure you have Flask installed.  



pip install Flask


 

Create a basic Flask application structure:

 

Flask Static Files with Examples

 

 

In this structure, we have:

  • `app.py`: The main Flask application file. 
  • `static/`: The folder for all static files, with subdirectories for CSS, JavaScript, and images.
  • `templates/`: The folder for HTML templates.

 


Example: Serving Static Files

 

Let's start by creating a simple Flask application in `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)


 

Creating HTML Template


In the `templates` folder, create an `index.html` file:

 


<!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 Example</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>Welcome to Flask Static Files Example with dailyaspirants</h1>
    <p>This is a demonstration of serving static files with Flask.</p>
    <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>



Adding CSS


Create a `style.css` file in `static/css/`:

 


body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    text-align: center;
    padding: 50px;
}

h1 {
    color: #333;
}

img {
    width: 200px;
    height: auto;
    margin-top: 20px;
}



Adding JavaScript


Create a `script.js` file in `static/js/`:

 


document.addEventListener('DOMContentLoaded', () => {
    console.log('JavaScript is loaded!');
});



 Adding an Image


Place an image named `logo.jpg` in `static/images/`. You can use any image for this example.


Read also: Implementing Basic Add to cart functionality in python using Flask

 

Running Your Flask Application


Now, run your Flask application:

 


python app.py



Open your browser and navigate to `http://127.0.0.1:5000/`. You should see a styled webpage with your static resources properly loaded.

 

Flask Static Files with Examples

 


 

Conclusion


Handling static files in Flask is straightforward and powerful, allowing you to organize and serve your assets efficiently. By following the steps outlined in this guide, you can enhance the functionality and appearance of your Flask web applications.

Feel free to experiment with more complex setups and additional static file types to suit your application's needs.

Previous Post Next Post