Flask 错误:werkzeug.routing.BuildError
我修改了flaskr示例应用的登录部分,但第一行出现了错误。不过www.html文件确实在模板目录里。
return redirect(url_for('www'))
#return redirect(url_for('show_entries'))
显示的错误:
werkzeug.routing.BuildError
BuildError: ('www', {}, None)
3 个回答
3
我遇到了一个错误
BuildError: ('project_admin', {}, None)
这个错误出现在我调用了
return redirect(url_for('project_admin'))
的时候,我想在我的蓝图中引用 project_admin
这个函数。为了解决这个错误,我在函数名之前加了一个点,变成这样:
return redirect(url_for('.project_admin'))
结果,问题就解决了。
4
假设已经定义了 def www():
(就像unmounted的精彩回答中提到的那样),这个错误也可能在你使用一个还没有注册的蓝图时出现。
确保在第一次创建 app
的时候就注册这些蓝图。对我来说,是这样做的:
from project.app.views.my_blueprint import my_blueprint
app = Flask(__name__, template_folder='{}/templates'.format(app_path), static_folder='{}/static'.format(app_path))
app.register_blueprint(my_blueprint)
然后在 my_blueprint.py
中:
from flask import render_template, Blueprint
from flask_cors import CORS
my_blueprint = Blueprint('my_blueprint', __name__, url_prefix='/my-page')
CORS(my_blueprint)
@metric_retriever.route('/')
def index():
return render_template('index.html', page_title='My Page!')
153
return redirect(url_for('www'))
这个写法可以用,如果你在其他地方有一个这样的函数:
@app.route('/welcome')
def www():
return render_template('www.html')
url_for
是用来查找一个函数的,你需要把你想调用的函数的 名字 传给它。可以这样理解:
@app.route('/login')
def sign_in():
for thing in login_routine:
do_stuff(thing)
return render_template('sign_in.html')
@app.route('/new-member')
def welcome_page():
flash('welcome to our new members')
flash('no cussing, no biting, nothing stronger than gin before breakfast')
return redirect(url_for('sign_in')) # not 'login', not 'sign_in.html'
你也可以用 return redirect('/some-url')
,如果这样更容易记住的话。根据你第一行的意思,可能你想要的只是 return render_template('www.html')
。
另外,根据下面shuaiyuancn的评论,如果你在使用蓝图,url_for
应该这样调用:url_for('blueprint_name.func_name')
注意你传的不是对象,而是字符串。 可以在这里查看文档。