[Python] Passing and Parsing JSON from Python script to HTML Template with Jinja2

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I have a python function which generates an HTML file. It fills in a few fields and a table with dynamic values based on the argument it receives with the help of Jinja2. This table has old value and new value which are a part of the json variable called diff_values. Now the table has a checkbox for each changed (diff) value and after selecting necessary checkboxes, it should replace the original JSON with the updated values for those key value pairs which was checked. Here is my code for doing this:

    helper.py

    import json
    from jinja2 import Environment, FileSystemLoader

    def create_html_content(diff_data):
    # Load the Jinja2 template
    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('template.html')

    # Prepare the data for rendering
    data = {
    'suite_name': diff_data['suite_name'],
    'test_case_name': diff_data['test_case_name'],
    'expected_json_path': diff_data['expected_json_path'],
    'diff': diff_data['diff']['values_changed'],
    'diff_values': json.dumps(diff_data['diff']).replace('</', '<\\/') # Avoid script injection
    }

    # Render the template with the data
    html_content = template.render(data)
    return html_content


    template.html

    <html>
    <head>
    <title>Differences</title>
    </head>
    <body>
    <h1>Difference Details</h1>
    <p>Suite: {{ suite_name }}</p>
    <p>Test Case: {{ test_case_name }}</p>
    <p>Expected JSON Path: {{ expected_json_path }}</p>
    <table border="1">
    <tr>
    <th>Select</th>
    <th>Attribute</th>
    <th>Old Value</th>
    <th>New Value</th>
    </tr>
    {% for key, value in diff.items() %}
    <tr>
    <td><input type="checkbox" data-attribute="{{ key }}"></td>
    <td>{{ key.split("root['")[1].split("']")[0] }}</td>
    <td>{{ value.old_value }}</td>
    <td>{{ value.new_value }}</td>
    </tr>
    {% endfor %}
    </table>
    <button onclick="submitSelected()">Accept Selected Changes</button>
    <script>
    function submitSelected() {
    var selectedDiffs = JSON.parse(JSON.stringify(diffValues)); // Deep copy of diffValues
    selectedDiffs.values_changed = {}; // Reset the values_changed object
    console.log("BEFORE FOR LOOP: ", selectedDiffs)
    document.querySelectorAll('input[type="checkbox"]:checked').forEach(function(checkbox) {
    var attribute = checkbox.getAttribute('data-attribute');
    console.log("INSIDE FOR LOOP, ATTRIBUTE:", attribute)
    console.log("INSIDE FOR LOOP, DIFF VAL: ", diffValues.values_changed[attribute])
    selectedDiffs.values_changed[attribute] = diffValues.values_changed[attribute];
    });
    console.log("AFTER: ", selectedDiffs);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:8000/submit", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.send(JSON.stringify(selectedDiffs));
    xhr.onload = function() {
    if (xhr.status == 200) {
    alert('Selected changes submitted');
    } else {
    alert('Failed to submit selected changes');
    }
    };
    }
    var diffValues = {{ diff_values | tojson }};
    </script>
    </body>
    </html>


    I am getting a linting issue in var diffValues = {{ diff_values | tojson }}; but not sure how to resolve it.

    Now my main problem is when I select the checkboxes and click Accept Selected Changes, I am getting the error:

    Uncaught TypeError: Cannot read properties of undefined (reading 'root['key1']')

    The logs as per the code are: BEFORE FOR LOOP: {"values_changed": {"root['key1']": {"new_value": "value1", "old_value": "value9"}, "root['key3']": {"new_value": "value3", "old_value": "value8"}}}

    INSIDE FOR LOOP, ATTRIBUTE: root['key1']

    After that its giving the errors so no more console logs. It's basically failing at accessing the key value pairs for "root['key1']" by doing diffValues.values_changed[attribute], but why is it failing when the key does exit?

    Continue reading...

Compartilhe esta Página