Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

werkzeug.routing.BuildError: Could not build url for endpoint

Tags:

python

flask

I have created a web API to render a webpage with navigation. Below is my code

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/testsite/')
def home():
    return render_template('home.html')
if __name__ == '__main__':
    app.run(debug=True)

@app.route('/about/')
def about():

        return render_template('about.html')

if __name__ == '__main__':
    app.run(debug=True)

Below is the HTML code for both html templates

home.html

<!DOCTYPE html>
<html>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="home">
<h1>My Personal Website</h1>
<p>Hi, this is my personal website.</p>
</div>
{% endblock %}
</body>
</html>

about.html

<!DOCTYPE html>
<html>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="about">
<h1>About me</h1>
<img src="{{ user_image }}" alt="User Image">
<p>Update about yourself here</p>
</div>
{% endblock %}

Now this example works perfectly fine. But when I try to use this to add code to make API for a machine learning mode.

Below is the code the for the same.

from flask import Flask, abort, request,render_template, json, render_template_string

from DataPreparationv4 import Data_Preprocess
import numpy as np
import pandas as pd
import pickle
from flask_jsonpify import jsonpify

pd.options.mode.chained_assignment = None

filename = 'CTA_Classification.pkl'
loaded_model = pickle.load(open(filename, 'rb'))

app = Flask(__name__)

@app.route("/", methods=['GET'])
def Predictions():

    Base_Data = pd.read_csv('Test.csv')
    DataSet1 = Data_Preprocess(Base_Data)

    [...]
    df_list = Predictions.values.tolist()

    return render_template('homev2.html', my_list=df_list)

if __name__ == '__main__':
    app.run(debug = True)

@app.route('/about/')
def about():
        return render_template('about.html')
if __name__ == '__main__':
    app.run(debug = True) 

Now, when I run this, I get the below error. I have even tried to change the return code to return render_template('homev2.html') but with same error.

werkzeug.routing.BuildError: Could not build url for endpoint 'home'. Did you mean 'about' instead?

Below is the code revised code for home.html named as homev2.html:

<!DOCTYPE html>
<html>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="home">
<h1>Predictions Page</h1>
<p><h4>Predictions</h4></p>
<table>
         <tbody>
         {# here we iterate over every item in our list#}
         {% for item in my_list %}
             <tr><td>{{ item }}</td></tr>
         {% endfor %}
         </tbody>
 </table>
</div>
{% endblock %}
</body>
</html>

layout.html

<!DOCTYPE html>
<html>
 <head>
    <title>Flask app</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
  </head>
  <body>
    <header>
      <div class="container">
        <h1 class="logo">The web app</h1>
        <strong><nav>
          <ul class="menu">
            <li><a href="{{ url_for('home') }}">Home</a></li>
            <li><a href="{{ url_for('about') }}">About</a></li>
          </ul>
        </nav></strong>
      </div>
    </header>
    <div class="container">
      {% block content %}
      {% endblock %}
    </div>
  </body>
</html>

Below is the full traceback

[2018-07-08 23:05:35,225] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\Deploy\Predictions.py", line 51, in Predictions
    return render_template('homev2.html', my_list=df_list)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\templating.py", line 135, in render_template
    context, ctx.app)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\templating.py", line 117, in _render
    rv = template.render(context)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\jinja2\environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\jinja2\_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "D:\Deploy\templates\homev2.html", line 4, in top-level template code
    {% extends "layout.html" %}
  File "D:\Deploy\templates\layout.html", line 13, in top-level template code
    <li><a href="{{ url_for('home') }}">Home</a></li>
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\helpers.py", line 356, in url_for
    return appctx.app.handle_url_build_error(error, endpoint, values)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2061, in handle_url_build_error
    reraise(exc_type, exc_value, tb)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\flask\helpers.py", line 345, in url_for
    force_external=external)
  File "C:\Users\sudhir_kb\Continuum\anaconda3\lib\site-packages\werkzeug\routing.py", line 1776, in build
    raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'home'. Did you mean 'about' instead?
127.0.0.1 - - [08/Jul/2018 23:05:35] "[1m[35mGET / HTTP/1.1[0m" 500 -

I don't understand why I am getting an error when I add the code to display the predictions as that's is only change. Where am I going wrong.

I am still a newbie and learning these concepts by researching in internet.

I have searched and did not find a similar issue even though the error is same in many posts hence created this. If this is a duplicate, please guide me to the original post.

Please help me in fixing this issue.

like image 306
kbsudhir Avatar asked Jul 08 '18 16:07

kbsudhir


Video Answer


1 Answers

After removing the first if __name__ statement, the error persists because you are calling the view home in your template layout.html :

File "D:\Deploy\templates\layout.html", line 13, in top-level template code
    <li><a href="{{ url_for('home') }}">Home</a></li>

so url_for tries to find a view called home but you replaced it with the view Predictions :

@app.route("/", methods=['GET'])
def Predictions():
    ...

So you can change the name of this function to home or change the call in your template to

<li><a href="{{ url_for('Predictions') }}">Home</a></li>
like image 102
PRMoureu Avatar answered Sep 18 '22 05:09

PRMoureu