General Question using Python, HTML file in local folder

I am looking for help in understanding how to achieve what I am trying to do. I have never used Python for anything similar, so this is new territory for me. My question is: Is it possible to have a Python script that interacts with an HTML file stored in a local folder and triggers the script to show output in the HTML file? What should be the steps to achieve this?

Sample of what I am trying to do:

My aim is to connect this HTML file:

import os

# Define the HTML content
html_content = """
<!DOCTYPE html>
<html>
</head>
<body>
    <h1>NABERS Intensity</h1>
    <label for="nla">NLA:</label>
    <input type="text" id="nla" name="nla"><br><br>
    <label for="building_grade">Building Grade:</label>
    <input type="text" id="building_grade" name="building_grade"><br><br>
    <button onclick="estimate()">Estimate</button><br><br>
    <div id="output"></div>

    <script>
        async function estimate() {
            var nla = document.getElementById('nla').value;
            var building_grade = document.getElementById('building_grade').value;
            var output = document.getElementById('output');
            
            const response = await fetch('/estimate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ nla: nla, building_grade: building_grade })
            });
            
            const result = await response.json();
            output.innerHTML = "Estimated values:<br>" + JSON.stringify(result, null, 2);
        }
    </script>
</body>
</html>
"""

# Define the file path
file_path = 'sample_file.html'

# Create the necessary directories if they don't exist
os.makedirs(os.path.dirname(file_path), exist_ok=True)

# Write the HTML content to the file in the specified folder
with open(file_path, 'w') as file:
    file.write(html_content)

print(f"HTML file 'sample_file.html' has been created successfully in the folder '{file_path}'.")

and when the user click estimate button it triggers a python scripts that is suppose to group the data by NLA and Building Grade and show the average hours as the output. Here is a sample that isn’t working yet.

import pandas as pd
import os

def calculate_nabers_intensity(nla, building_grade):
    # Define the file path for the Excel file
    excel_file_path = 'sample_data_file.xlsx'
    
    # Read the Excel file
    df = pd.read_excel(excel_file_path)
    
    # Define NLA ranges
    nla_ranges = [
        (0, 10000),
        (11000, 20000),
        (21000, 30000),
        (31000, 40000),
        (41000, 50000),
        (51000, 60000),
        (61000, 70000),
        (71000, 80000),
        (81000, 90000),
        (91000, 100000)
    ]
    
    # Group by 'Grade' and 'NLA' ranges
    results = {}
    for grade in df['Grade'].unique():
        grade_df = df[df['Grade'] == grade]
        for nla_range in nla_ranges:
            range_df = grade_df[(grade_df['NLA'] >= nla_range[0]) & (grade_df['NLA'] <= nla_range[1])]
            average_weight = range_df['total weight'].mean()
            results[f"{grade} ({nla_range[0]}-{nla_range[1]})"] = average_weight
    
    return results

results = calculate_nabers_intensity(nla, building_grade)
print(results)

My biggest issue is that I don’t know how I am suppose to connect the HTML file with the python script.

Here is data sample:

NLA (column header)
1000
70000
30000
40000
10000
20000

Building Grade (column header)
A
A
B
C
B
A

Hours (column header)
20
20
30
40
10
40

Any guidance most appreciated. Thank you in advance.

Earth2000

The traditional way is to build a website that sends that fetch request to a Python back end (or service), that runs the Python code on a server or cloud engine. The latter can easily be built with Flask, Django, FastAPI, or many other frameworks.

Jupyter worksheets have a nice browser interface out of the box, if that’s all that’s needed.

It never gained popularity, but there’s always been Brython. Alternatively, they run Python in completely different environments (to regular CPython’s python.exe), but in recent years thanks to WASM, it’s also possible to run Python in the browser with Pyodide or Pyscript. No server is required then, just static file hosting.

https://pyodide.org/en/stable/console.html

2 Likes

Yes. You will have to learn how to use Python to make a website/webpage. It can do that though. Start looking for tutorials.

  1. A search for tutorials to get you started: https://www.youtube.com/results?search_query=python+tutorial+beginner+web+page
  2. YT channels I like: Tech with Tim, Freecodecamp, Indently. Start with those and see if you like their teaching style.
  3. To make a website with Python you use a “framework”. There are a handful of frameworks you can use with Python to make websites. Flask is just one of them.
  4. I recommend finding a tutorial that is no older than 1 year. Otherwise you might have problems with old modules that will not work with new Python. I had the same problems in some cases.

Thank you for sharing James and Chuck.