机器学习 Flask 应用程序中的错误 - jinja2.exceptions.TemplateNotFound:index.html

问题描述 投票:0回答:1

我正在做一个关于电动汽车价格预测的机器学习 Flask 项目。我已经被一个问题困扰了两天了。

运行

python run.py
命令后,我在本地主机上收到此错误:

TemplateNotFound
jinja2.exceptions.TemplateNotFound: index.html

Traceback (most recent call last)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 1498, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 1476, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 1473, in wsgi_app
response = self.full_dispatch_request()Open an interactive python shell in this frame
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 882, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 880, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 865, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
File "G:\Machine_Learning_Projects\2024\electric_vehicle_price_prediction_2\app\routes.py", line 7, in index
return render_template('index.html')
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\templating.py", line 149, in render_template
template = app.jinja_env.get_or_select_template(template_name_or_list)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\environment.py", line 1084, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\environment.py", line 1013, in get_template
return self._load_template(name, globals)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\environment.py", line 972, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\loaders.py", line 126, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\templating.py", line 65, in get_source
return self._get_source_fast(environment, template)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\templating.py", line 99, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: index.html
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

这是我在应用程序文件夹内的

routes.py
文件中的代码:

from flask import render_template, request, jsonify
from app import app
from app.model import predict_price

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    data = request.form.to_dict()
    
    # Convert the form data into the correct format for prediction
    features = [
        data['county'],
        data['city'],
        data['zip_code'],
        data['model_year'],
        data['make'],
        data['model'],
        data['ev_type'],
        data['cafv_eligibility'],
        data['legislative_district']
    ]
    
    # Get the prediction result
    price = predict_price(features)
    
    return jsonify({'predicted_price': price}

这是我在模板文件夹内的

index.html
文件中的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EV Price Prediction</title>
</head>
<body>
    <h1>Electric Vehicle Price Prediction</h1>
    
    <form action="/predict" method="POST">
        <label for="county">County:</label>
        <input type="text" id="county" name="county"><br><br>

        <label for="city">City:</label>
        <input type="text" id="city" name="city"><br><br>

        <label for="zip_code">ZIP Code:</label>
        <input type="text" id="zip_code" name="zip_code"><br><br>

        <label for="model_year">Model Year:</label>
        <input type="text" id="model_year" name="model_year"><br><br>

        <label for="make">Make:</label>
        <input type="text" id="make" name="make"><br><br>

        <label for="model">Model:</label>
        <input type="text" id="model" name="model"><br><br>

        <label for="ev_type">Electric Vehicle Type:</label>
        <input type="text" id="ev_type" name="ev_type"><br><br>

        <label for="cafv_eligibility">CAFV Eligibility:</label>
        <input type="text" id="cafv_eligibility" name="cafv_eligibility"><br><br>

        <label for="legislative_district">Legislative District:</label>
        <input type="text" id="legislative_district" name="legislative_district"><br><br>

        <input type="submit" value="Predict">
    </form>
    
    <div id="result">
        {% if predicted_price %}
            <h2>Predicted Price: ${{ predicted_price }}</h2>
        {% endif %}
    </div>
</body>
</html>

这是我的 GitHub 存储库:

https://github.com/MdEhsanulHaqueKanan/electric-vehicle-price-prediction-2

在网上查看其他类似的问题,我认为我的项目文件夹结构可能有问题。但我已经仔细检查了我的文件夹结构。我还没发现有什么问题。

您可以在这里看到我的项目文件夹结构:

ev_price_prediction/
│
├── app/
│   ├── __init__.py
│   ├── routes.py
│   └── model.py
│
├── static/
│   └── style.css
│
├── templates/
│   └── index.html
│
├── dataset/
│   └── train.csv
│   └── test.csv
│
├── requirements.txt
└── run.py

您能帮我解决这个问题吗?

python machine-learning flask
1个回答
0
投票

官方文档中所述:

Jinja uses a central object called the template Environment. Instances of this class are used to store the configuration and global objects, and are used to load templates from the file system or other locations

所以你需要先创建一个模板环境,例如:

env = Environment(
    loader=PackageLoader("app"),
    autoescape=select_autoescape()
)

然后将

template
目录移动到你的
app
目录下:

 ev_price_prediction/
│
├── app/
│   ├── __init__.py
│   ├── routes.py
│   ├── model.py
│   └── templates/
│       └── index.html 
│
├── static/
│   └── style.css
│
│
├── dataset/
│   └── train.csv
│   └── test.csv
│
├── requirements.txt
└── run.py

然后就可以从模板环境加载模板了:

@app.route('/')
def index():
    env = Environment(
        loader=PackageLoader("app"),
        autoescape=select_autoescape()
    )
    template = env.get_template("index.html")
    return render_template(template)
© www.soinside.com 2019 - 2024. All rights reserved.