werkzeug.routing.BuildError:无法为端点建立网址

时间:2018-07-08 16:58:47

标签: python flask

我创建了一个Web API来呈现带有导航的网页。下面是我的代码

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)

下面是两个html模板的HTML代码

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 %}

现在,此示例可以正常运行。但是,当我尝试使用它来添加代码以使API成为机器学习模式时。

下面是相同的代码。

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) 

现在,当我运行此命令时,出现以下错误。我什至尝试将返回码更改为return render_template('homev2.html'),但有相同的错误。

  

werkzeug.routing.BuildError:无法为端点“ home”构建URL。您是说“关于”吗?

以下是home.html的代码修订代码,名为 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>

下面是完整的追溯

[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 -

我不明白为什么在添加代码以显示预测时出现错误,因为那只是变化。我要去哪里错了。

我仍然是新手,正在通过互联网研究来学习这些概念。

我搜索并没有找到类似的问题,尽管许多帖子中的错误相同,因此创建了此问题。如果这是重复的邮件,请引导我转到原始帖子。

请帮助我解决此问题。

2 个答案:

答案 0 :(得分:4)

删除第一条if __name__语句后,该错误仍然存​​在,因为您正在模板home中调用视图layout.html

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

所以url_for试图找到一个名为home的视图,但是您将其替换为视图Predictions

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

因此您可以将此函数的名称更改为home或将模板中的调用更改为

<li><a href="{{ url_for('Predictions') }}">Home</a></li>

答案 1 :(得分:0)

删除第一个if __name__ == 'main':块,只在底部保留一个。

Python文件自上而下“执行”。您不想在所有app.run()执行完毕(即建立路线)之前执行@app.route()。为什么详细说明值得探讨。