Skip to content
  • There are no suggestions because the search field is empty.

Flask Python Tutorial for Beginners: Part 3 - Dynamic HTML and Serving Static Folders

When building a web application with Flask, it is customary to incorporate static files like images, CSS, and JavaScript files. These files remain unchanged throughout the application's runtime. Flask offers a convenient method to manage these files.

 

 

Code Block
# Setting up a static folder in Flask
app = Flask(__name__, static_folder='static')

By default, Flask looks for static files in the 'static' folder. Here, we can store our images, CSS, and JavaScript files, and Flask will serve them efficiently.

Rendering Dynamic Content

Dynamic content in Flask refers to the data that changes based on user interaction or other factors. We use templates to render this dynamic content. Flask integrates with the Jinja2 template engine, which allows for dynamic data presentation in HTML files.

Code Block
# Rendering a template with dynamic content
@app.route('/')
def home():
return render_template('index.html', dynamic_data=dynamic_data)

In this example, 'dynamic_data' could be any Python data structure, like a list or dictionary. The 'index.html' template will use this data to render content dynamically.

Combining Static and Dynamic Content

A typical Flask application will use a combination of static and dynamic content. Static files like CSS and images style the page, while dynamic content keeps the data fresh and relevant.

Here's an example of how a Flask application can serve a static image while displaying dynamic data:

Code Block
# Example Flask application structure
/static
    /images
        - photo.jpg
/templates
    - index.html

# Python code
@app.route('/')
def home():
    image_url = url_for('static', filename='images/photo.jpg')
    return render_template('index.html', image_url=image_url)

In 'index.html', you can use the image URL to display the photo alongside dynamic content pulled from a database or API.

Conclusion

Flask is a powerful and flexible micro-framework for web development. By understanding how to serve static files and render dynamic content, you can create rich, interactive web applications. Remember to keep exploring Flask's features and capabilities to build even more complex and efficient web solutions.