Table of contents

  1. Python Flask shutdown event handler
  2. Flask Python Buttons
  3. Python flask ImmutableMultiDict
  4. Python Flask - ImmutableMultiDict

Python Flask shutdown event handler

In Flask, you can register a shutdown event handler to perform certain actions when the application is being shut down, such as cleaning up resources or performing final operations. To achieve this, you can use the @app.before_request decorator with a custom function. Here's how you can create a shutdown event handler in Flask:

from flask import Flask
import atexit

app = Flask(__name__)

# Register a function to be called when the application is shutting down
def shutdown():
    print("Shutting down... Perform cleanup here.")


def hello():
    return "Hello, Flask!"

if __name__ == '__main__':

In this example:

  1. The shutdown function is defined to handle cleanup operations when the application is being shut down.

  2. The atexit.register function is used to register the shutdown function to be executed when the application exits.

  3. The @app.route decorator defines a simple route for demonstration purposes.

  4. The if __name__ == '__main__': block ensures that the development server is only started when the script is run directly (not imported as a module).

When you run the Flask application and then stop it (e.g., by pressing Ctrl+C), the shutdown function will be called, allowing you to perform any necessary cleanup operations before the application exits.

Keep in mind that the atexit module works for simple use cases, but for more complex scenarios or production environments, you might need to consider other mechanisms or tools for graceful shutdown and resource cleanup, such as signals, event loops, and proper deployment strategies.

Flask Python Buttons

In a Flask web application, you can create buttons using HTML <button> elements in your HTML templates. These buttons can trigger actions when clicked, such as submitting a form, navigating to a different page, or executing JavaScript code. Here's how you can create buttons in Flask:

  1. HTML Buttons in Flask Templates:

    You can use standard HTML <button> elements within your Flask templates to create buttons. Here's an example:

    <!DOCTYPE html>
        <title>Flask Buttons</title>
        <h1>Buttons Example</h1>
        <!-- Submit Button for a Form -->
        <form action="/submit" method="post">
            <button type="submit">Submit Form</button>
        <!-- Link Button to Navigate to Another Page -->
        <a href="/another-page">
            <button>Go to Another Page</button>
        <!-- Button with JavaScript Action -->
        <button onclick="myFunction()">Click Me</button>
            function myFunction() {
                alert("Button clicked!");

    In this example, we create three buttons:

    • A submit button within a form that will submit the form to the /submit route.
    • A button within a link (<a>) that navigates to the /another-page route.
    • A button with an associated JavaScript function that displays an alert when clicked.
  2. Flask Routes and Handling Button Actions:

    In your Flask application, you need to define routes that handle the actions triggered by these buttons. For example, you might have routes like this:

    from flask import Flask, render_template
    app = Flask(__name__)
    def index():
        return render_template('index.html')
    @app.route('/submit', methods=['POST'])
    def submit_form():
        # Handle form submission logic here
        return "Form submitted successfully!"
    def another_page():
        return "You have navigated to another page."
    if __name__ == '__main__':

    In this code, when the form is submitted, it goes to the /submit route, where you can handle the form submission logic. The /another-page route simply returns a message when you click the button with the link.

  3. Templates and Static Files:

    Make sure you have a Flask template (e.g., index.html) that includes the HTML code for your buttons. Also, consider placing your JavaScript code in a separate file and serving static files using Flask's static folder for cleaner organization.

    Here's a common project structure:

    ������ templates/
    ��   ������ index.html
    ������ static/
    ��   ������ scripts/
    ��       ������ myscript.js

    You can reference your JavaScript file in the HTML template using:

    <script src="{{ url_for('static', filename='scripts/myscript.js') }}"></script>

That's it! With this setup, you can create buttons in your Flask web application and define routes to handle the actions associated with those buttons.

Python flask ImmutableMultiDict

In Flask, an ImmutableMultiDict is a special type of data structure that represents a dictionary with potentially multiple values per key. It's used to store data from incoming HTTP requests, such as form data or query parameters.

The reason it's called "Immutable" is because once it's created, you cannot modify the data in the ImmutableMultiDict. This immutability is helpful for preserving the original request data and preventing unintended modifications.

Here's how you can work with ImmutableMultiDict in a Flask application:

  1. Getting Data from Request: When you receive an HTTP request in your Flask route, you can access the request data using request.form for form data (POST requests) or request.args for query parameters (GET requests). Both request.form and request.args return an ImmutableMultiDict.

    from flask import Flask, request
    app = Flask(__name__)
    @app.route('/submit', methods=['POST'])
    def submit_form():
        data = request.form  # or request.args for query parameters
        # Access data using keys
        username = data.get('username')
        return f'Hello, {username}!'
  2. Working with Multi-Valued Data: When you have multiple values per key (e.g., multiple checkboxes with the same name), you can use methods like .getlist() to retrieve a list of values for a particular key.

    @app.route('/checkboxes', methods=['POST'])
    def handle_checkboxes():
        data = request.form
        selected_values = data.getlist('checkbox_name')
        return f'Selected values: {", ".join(selected_values)}'

Remember that ImmutableMultiDict is read-only, so you can't modify it directly. If you need to manipulate the data, you can convert it to a regular Python dictionary using the .to_dict() method:

data_dict = request.form.to_dict()

Flask provides a convenient and reliable way to work with incoming request data, and using ImmutableMultiDict helps ensure the integrity of the original data.

Python Flask - ImmutableMultiDict

ImmutableMultiDict is a data structure in Flask, specifically in its subpackage Werkzeug. It is essentially a dictionary that can have multiple values for the same key. This structure is especially useful for representing the form data that comes from HTML forms, where you can have multiple input fields with the same name.

In Flask, when you access request.form or request.args, you're often dealing with an ImmutableMultiDict.

Here's a simple explanation and demonstration:

  • Multiple Values for a Single Key: As its name suggests, you can have multiple values for a single key in an ImmutableMultiDict.

  • Immutable: This means that once this structure is created, you cannot modify it (add, remove, or change its items). If you need to modify it, you'd typically convert it to a mutable structure first.

  • Usage:

Let's assume you have an HTML form:

<form method="post">
    <input type="checkbox" name="hobby" value="reading" checked>
    <input type="checkbox" name="hobby" value="swimming">
    <input type="checkbox" name="hobby" value="coding" checked>
    <input type="submit" value="Submit">

If a user submits this form, multiple hobbies can be sent with the same key name "hobby".

In Flask, you can access these as:

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def form_data():
    hobbies = request.form.getlist('hobby')
    return ', '.join(hobbies)

if __name__ == '__main__':

In this example, request.form is an ImmutableMultiDict. Using the method .getlist('hobby'), you can retrieve all values associated with the key 'hobby' as a list.

  • Converting to a regular dictionary:

If you want to convert the ImmutableMultiDict to a regular dictionary, be aware that since dictionary keys must be unique, you'll only get the last value if there are multiple values for the same key:

data_dict = dict(request.form)

If you want to convert it to a dictionary and preserve all values for keys that have multiple values, you might do something like:

data_dict = {key: request.form.getlist(key) if len(request.form.getlist(key)) > 1 else request.form.getlist(key)[0] for key in request.form.keys()}

This will give you a dictionary where each key has either a single value or a list of values, depending on the number of values associated with that key in the ImmutableMultiDict.

More Python Questions

More C# Questions