【问题标题】:Flask error: werkzeug.routing.BuildError烧瓶错误:werkzeug.routing.BuildError
【发布时间】:2011-04-10 15:10:59
【问题描述】:

我修改了flaskr示例应用的登录,第一行报错。但是 www.html 在模板目录中。

return redirect(url_for('www'))
#return redirect(url_for('show_entries'))

显示错误:

werkzeug.routing.BuildError

BuildError: ('www', {}, None) 

【问题讨论】:

    标签: python flask


    【解决方案1】:

    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') 注意你不是传递对象,而是字符串。 @987654321 @。

    【讨论】:

    • +1 是一个非常清楚的例子......以及“没有什么比早餐前的杜松子酒强”
    • Blueprint 也有同样的问题 =/
    • 对于蓝图,将@app 替换为您的蓝图名称。 @app.route('xx') 变为 @blueprint_name.route('xx')
    • 蓝图应该是url_for('blue_print.func_name'),如flask.pocoo.org/docs/0.10/blueprints/#building-urls所示
    • 我认为@shuaiyuancn 的评论值得一提——显然这是我的错误。当它可能对其他人有用时,将其作为评论往往会将其埋在 SO 的折叠算法中。
    【解决方案2】:

    假设 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!')
    

    【讨论】:

    • 我在使用 pytest 装饰器而不使用 functools 库中的 wraps 时特别经历了这一点。添加了蓝图,瞧,问题解决了。 Flask functools ?
    【解决方案3】:

    我遇到了这个错误

    BuildError: ('project_admin', {}, None)

    当我接到这样的电话时

    return redirect(url_for('project_admin'))

    我试图在我的蓝图中引用 project_admin 函数。为了解决这个错误,我在函数名称前添加了一个点,如下所示:

    return redirect(url_for('.project_admin'))

    瞧,我的问题解决了。

    【讨论】:

    • 我遇到了这个问题,无论出于何种原因,添加点也为我解决了这个问题。之后我什至不需要保留这个点——就像它踢了 Flask/Blueprint/Something 并强迫它自行修复。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2018-10-02
    • 2021-04-29
    • 2013-08-19
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多