How to resolve not found error?

How do I resolve the not found error, when I press run, it shows a screen saying not found instead of going to my page.

from flask import Flask, request, render_template
import plotly.express as px
import pandas as pd
import secrets

app = Flask(__name__)
app.secret_key = secrets.token_hex(16)

def generate_html_table(vehicle_data):
  # Function to generate an HTML table for vehicle data
  html_table = "<table border='1'><tr><th>Vehicle</th>"

  # Add header row
  for key in vehicle_data[next(iter(vehicle_data))].keys():
      html_table += f"<th>{key}</th>"
  html_table += "</tr>"

  # Add data rows
  for vehicle, data in vehicle_data.items():
      html_table += f"<tr><td>{vehicle}</td>"
      for value in data.values():
          html_table += f"<td>{value}</td>"
      html_table += "</tr>"

  html_table += "</table>"
  return html_table
  
# Electric Vehicle Data
ve_data = {
    "Tesla Model Y": {"PDSF": 46990, "Co├╗t de l'├ęlectricit├ę": "13c/kWh", "Distance/an": "24 000 km/an", "Maintien et repair ($)": 5173, "Co├╗t de l'assurance": 7400, "Autres co├╗ts": 16510, "Total apr├Ęs 5 ans($)": 76541, "├ëconomie de carburant EPA": "", "Sauver ou d├ępenser?": "Sauver 5 750$", "P├ętrolium": "0 barils", "├ëmissions": "0 grammes"},
    "Tesla Model 3": {"PDSF": 35000, "Co├╗t de l'├ęlectricit├ę": "13c/kWh", "Distance/an": "24 000 km/an", "Maintien et repair ($)": 4213, "Co├╗t de l'assurance": 7400, "Autres co├╗ts": 17986, "Total apr├Ęs 5 ans($)": 67939, "├ëconomie de carburant EPA": "289 (303 / 273)", "Sauver ou d├ępenser?": "Sauver 6000$", "P├ętrolium": "0 barils", "├ëmissions": "0 grammes"},
    "Ford Mustang Mach-E": {"PDSF": 42995, "Co├╗t de l'├ęlectricit├ę": "13c/kWh", "Distance/an": "24 000 km/an", "Maintien et repair ($)": 4663, "Co├╗t de l'assurance": 5633, "Autres co├╗ts": 11807, "Total apr├Ęs 5 ans($)": 67438, "├ëconomie de carburant EPA": "266 (278 / 252)", "Sauver ou d├ępenser?": "Sauver 4750$", "P├ętrolium": "0 barils", "├ëmissions": "0 grammes"},
    "Tesla Model X": {"PDSF": 101380, "Co├╗t de l'├ęlectricit├ę": "13c/kWh", "Distance/an": "24 000 km/an", "Maintien et repair ($)": 4935, "Co├╗t de l'assurance": 7759, "Autres co├╗ts": 42018, "Total apr├Ęs 5 ans($)": 158522, "├ëconomie de carburant EPA": "219 (233 / 202)", "Sauver ou d├ępenser?": "Sauver 5500$", "P├ętrolium": "0 barils", "├ëmissions": "0 grammes"},
    "Tesla Model S": {"PDSF": 89990, "Co├╗t de l'├ęlectricit├ę": "13c/kWh", "Distance/an": "24 000 km/an", "Maintien et repair ($)": 4705, "Co├╗t de l'assurance": 7759, "Autres co├╗ts": 31970, "Total apr├Ęs 5 ans($)": 136764, "├ëconomie de carburant EPA": "240 (252 / 228)", "Sauver ou d├ępenser?": "Sauver 6000$", "P├ętrolium": "0 barils", "├ëmissions": "0 grammes"},
    "Chevrolet Bolt EUV": {"PDSF": 27800, "Co├╗t de l'├ęlectricit├ę": "13c/kWh", "Distance/an": "24 000 km/an", "Maintien et repair ($)": 3527, "Co├╗t de l'assurance": 4832, "Autres co├╗ts": 10520, "Total apr├Ęs 5 ans($)": 48551, "├ëconomie de carburant EPA": "282 (292 / 270)", "Sauver ou d├ępenser?": "Sauver 6000$", "P├ętrolium": "0 barils", "├ëmissions": "0 grammes"},
}

# Gas Vehicle Data
gas_data = {
    "Ford F-150": {"PDSF": 33695, "Co├╗t du gaz": "140c/litre", "Distance/an": "24 000 km/an", "Maintien et repair": 6129, "Co├╗t de l'assurance": 4364, "Autres co├╗ts": 17019, "Total apr├Ęs 5 ans ($)": 78277, "├ëconomie de carburant": "49 (42 / 56)", "Sauver ou d├ępenser?": "D├ępenser 3250$", "P├ętrolium": "3.75 barils", "├ëmissions": "267 grammes"},
    "Chevrolet Silverado": {"PDSF": 40500, "Co├╗t du gaz": "140c/litre", "Distance/an": "24 000 km/an", "Maintien et repair": 3916, "Co├╗t de l'assurance": 4804, "Autres co├╗ts": 15973, "Total apr├Ęs 5 ans ($)": 81973, "├ëconomie de carburant": "47 (45 / 49)", "Sauver ou d├ępenser?": "D├ępenser 3750$", "P├ętrolium": "3.94 barils", "├ëmissions": "277 grammes"},
    "Ram Pickup": {"PDSF": 36820, "Co├╗t du gaz": "140c/litre", "Distance/an": "24 000 km/an", "Maintien et repair": 4659, "Co├╗t de l'assurance": 4740, "Autres co├╗ts": 15991, "Total apr├Ęs 5 ans ($)": 79010, "├ëconomie de carburant": "40 (35 / 52)", "Sauver ou d├ępenser?": "D├ępenser 3750$", "P├ętrolium": "3.94 barils", "├ëmissions": "277 grammes"},
    "Toyota RAV-4": {"PDSF": 27575, "Co├╗t du gaz": "140c/litre", "Distance/an": "24 000 km/an", "Maintien et repair": 5490, "Co├╗t de l'assurance": 4160, "Autres co├╗ts": 9913, "Total apr├Ęs 5 ans ($)": 62530, "├ëconomie de carburant": "71 (64 / 80)", "Sauver ou d├ępenser?": "Sauver 250$", "P├ętrolium": "2.72 barils", "├ëmissions": "190 grammes"},
}

selected_ve = None
selected_gaz = None

home_template = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 1em;
        }

        section {
            max-width: 600px;
            margin: 20px auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1, h2 {
            text-align: center;
        }

        p {
            text-align: justify;
        }

        a {
            display: block;
            margin: 10px 0;
            padding: 10px;
            background-color: #333;
            color: white;
            text-align: center;
            text-decoration: none;
            border-radius: 4px;
        }

        a:hover {
            background-color: #555;
        }
    </style>
</head>
<body>
    <header>
        <h1>Welcome to the Vehicle Comparison Tool</h1>
    </header>

    <section>
        <h2>About the Tool</h2>
        <p>This tool allows you to compare the costs of different electric and gasoline vehicles over a 5-year period. It takes into account various factors such as purchase price, fuel costs, and maintenance expenses.</p>

        <a href="https://evetgazwonkai21repl.wordpress.com">Read the Article</a>
        <a href="/vehicle-comparison">Go to Vehicle Comparison Tool</a>
    </section>
</body>
</html>
"""

comparison_template = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vehicle Comparison Tool</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 1em 0;
        }

        section {
            max-width: 600px;
            margin: 20px auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        form {
            text-align: left;
        }

        label {
            display: block;
            margin-bottom: 10px;
        }

        select, input[type="text"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        input[type="submit"] {
            background-color: #333;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        input[type="submit"]:hover {
            background-color: #555;
        }

        .result {
            margin-top: 20px;
            text-align: center;
        }

        .graph {
            margin-top: 20px;
        }

        .table-container {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <header>
        <h1>Vehicle Comparison Tool</h1>
    </header>

    <section>
        <form method="post">
            <label for="ve-options">Choose an Electric Vehicle:</label>
            <select id="ve-options" name="ve-options">
                {{ ve_option_html | safe }}
            </select>

            <label for="ve-pdsf">Electric Vehicle PDSF ($):</label>
            <input type="text" id="ve-pdsf" name="ve-pdsf" pattern="\d+(\.\d{1,2})?" required>

            <label for="gaz-options">Choose a Gasoline Vehicle:</label>
            <select id="gaz-options" name="gaz-options">
                {{ gaz_option_html | safe }}
            </select>

            <label for="gaz-pdsf">Gasoline Vehicle PDSF ($):</label>
            <input type="text" id="gaz-pdsf" name="gaz-pdsf" pattern="\d+(\.\d{1,2})?" required>

            <label for="gas-cost">Gasoline Cost ($/gallon):</label>
            <input type="text" id="gas-cost" name="gas-cost" pattern="\d+(\.\d{1,2})?" required>

            <label for="elec-cost">Electricity Cost ($/kWh):</label>
            <input type="text" id="elec-cost" name="elec-cost" pattern="\d+(\.\d{1,2})?" required>

            <label for="miles-year">Number of Miles Per Year:</label>
            <input type="text" id="miles-year" name="miles-year" pattern="\d+(\.\d{1,2})?" required>

            <label for="maintenance-cost">Maintenance Estimates:</label>
            <input type="text" id="maintenance-cost" name="maintenance-cost" pattern="\d+(\.\d{1,2})?" required>

            <label for="other-cost">Other Costs:</label>
            <input type="text" id="other-cost" name="other-cost" pattern="\d+(\.\d{1,2})?" required>

            <input type="submit" value="Compare">
        </form>

        <div class="result">
            {{ vehicle_info | safe }}
        </div>

        <div class="graph">
            {{ graph | safe }}
        </div>

        <div class="table-container">
            <h2>Electric Vehicle Data</h2>
            {{ ve_html_table | safe }}

            <h2>Gas Vehicle Data</h2>
            {{ gas_html_table | safe }}
        </div>
    </section>
</body>
</html>
"""

@app.route('/vehicle-comparison', methods=['GET', 'POST'])
def index():
    global selected_ve, selected_gaz

    ve_option_html = ''.join(f'<option value="{ve}">{ve}</option>' for ve in ve_options.keys())
    gaz_option_html = ''.join(f'<option value="{gaz}">{gaz}</option>' for gaz in gaz_options.keys())

    if request.method == 'POST':
        selected_ve = request.form.get('ve-options')
        selected_gaz = request.form.get('gaz-options')

    vehicle_info = compare_options()
    graph = create_graph(selected_ve, selected_gaz)

    # Generate HTML tables
    ve_html_table = generate_html_table(ve_options)
    gas_html_table = generate_html_table(gaz_options)

    return render_template('index.html', ve_option_html=ve_option_html, gaz_option_html=gaz_option_html, vehicle_info=vehicle_info, graph=graph, ve_html_table=ve_html_table, gas_html_table=gas_html_table)


def calculate_costs(vehicle, gas_cost, elec_cost, miles_per_year, maintenance, other_costs):
    gas_total_cost = ve_options[vehicle]["gas_cost"] * miles_per_year
    elec_total_cost = ve_options[vehicle]["elec_cost"] * ve_options[vehicle]["values"][-1] * miles_per_year
    maintenance_total_cost = ve_options[vehicle]["maintenance_cost"] * miles_per_year
    other_total_costs = ve_options[vehicle]["other_costs"] * miles_per_year
    total_cost = ve_options[vehicle]["PDSF"] + gas_total_cost + elec_total_cost + maintenance_total_cost + other_total_costs
    return total_cost

def create_graph(selected_ve, selected_gaz):
    if selected_ve and selected_gaz:
        ve_values = ve_options[selected_ve]["values"]
        ve_pollution = ve_options[selected_ve]["pollution"]
        gaz_values = gaz_options[selected_gaz]["values"]
        gaz_pollution = gaz_options[selected_gaz]["pollution"]

        max_length = max(len(ve_values), len(ve_pollution), len(gaz_values), len(gaz_pollution))
        ve_values = ve_values + [0] * (max_length - len(ve_values))
        ve_pollution = ve_pollution + [0] * (max_length - len(ve_pollution))
        gaz_values = gaz_values + [0] * (max_length - len(gaz_values))
        gaz_pollution = gaz_pollution + [0] * (max_length - len(gaz_pollution))

        ve_data = {
            'Type': [f'{selected_ve} - {i}Y' for i in range(1, max_length + 1)],
            'Cost (in US dollars)': ve_values,
        }
        gaz_data = {
            'Type': [f'{selected_gaz} - {i}Y' for i in range(1, max_length + 1)],
            'Cost (in US dollars)': gaz_values,
        }

        ve_df = pd.DataFrame(ve_data)
        gaz_df = pd.DataFrame(gaz_data)

        fig = px.line(ve_df, x='Type', y='Cost (in US dollars)', title=f'Cost Comparison - {selected_ve} vs {selected_gaz}')
        fig.add_scatter(x=gaz_df['Type'], y=gaz_df['Cost (in US dollars)'], mode='lines', name=selected_gaz, line=dict(color='red'))

        fig.update_layout(
            xaxis_title='Type',
            yaxis_title='Cost (in US dollars)',
            title=f'Cost Comparison - {selected_ve} vs {selected_gaz}',
            xaxis=dict(zeroline=True, zerolinewidth=1, zerolinecolor='black'),
            yaxis=dict(zeroline=True, zerolinewidth=1, zerolinecolor='black')
        )

        civic_models = ["Honda Civic LX", "Honda Civic", "Tesla Model 3", "Honda Civic Touring"]
        civic_costs = [25933, 28289, 30378, 31476]
        electric_costs = ve_values[:len(civic_models)]

        cost_data = {
            'Type': civic_models + [f'{selected_ve} - {i}Y' for i in range(1, len(civic_models) + 1)],
            'Cost (in US dollars)': civic_costs + electric_costs
        }

        cost_df = pd.DataFrame(cost_data)

        cost_fig = px.bar(cost_df, x='Type', y='Cost (in US dollars)', title=f'5-Year Ownership Cost Comparison - {selected_ve} vs Honda Civic')

        cost_fig.update_traces(marker_color=['#1f77b4', '#1f77b4', 'red', '#1f77b4'])

        cost_fig.update_layout(
            xaxis_title='Type',
            yaxis_title='Cost (in US dollars)',
            title=f'5-Year Ownership Cost Comparison - {selected_ve} vs Honda Civic',
            xaxis=dict(zeroline=True, zerolinewidth=1, zerolinecolor='black'),
            yaxis=dict(zeroline=True, zerolinewidth=1, zerolinecolor='black')
        )

        graph = fig.to_html(full_html=True) + cost_fig.to_html(full_html=True)

        cost_text = '<p class="cost-text">Costs: 3.10 $/gallon for gasoline and 0.13 $/kWh for electricity, 15,000 miles per year, maintenance estimates from Edmunds and Paul Fosse/CleanTechnica, $3,750 tax credit for the Model 3, $5,000 down payment, and a 5.5% 5-year loan for the remaining car costs. Kelley Blue Book estimates the resale value over 5 years.</p>'

        graph += cost_text

        return graph

    return ""

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=81, debug=True)

ItÔÇÖs because, by default (in the WebView), Replit is loading the / path to your server. Since you never said @app.route('/'), then it wonÔÇÖt show. You have to visit the paths that you declared in the code.

3 Likes

Hi @wonkai21 , welcome to the forums!
You need to add the line @app.route('/') before each def() statement, on the line above. Each route should be different.
For example, the first def() could look like this:

@app.route('/')
def generate_html_table(vehicle_data):
  # Function to generate an HTML table for vehicle data
  html_table = "<table border='1'><tr><th>Vehicle</th>"

  # Add header row
  for key in vehicle_data[next(iter(vehicle_data))].keys():
      html_table += f"<th>{key}</th>"
  html_table += "</tr>"

  # Add data rows
  for vehicle, data in vehicle_data.items():
      html_table += f"<tr><td>{vehicle}</td>"
      for value in data.values():
          html_table += f"<td>{value}</td>"
      html_table += "</tr>"

  html_table += "</table>"
  return html_table

Hope this helps!

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.