【问题标题】:python flask url_for is throwing constant werkzeug build errorspython flask url_for 抛出常量 werkzeug 构建错误
【发布时间】:2014-10-20 06:13:06
【问题描述】:

我在一个非常简单的应用程序中遇到烧瓶 url_for('') 错误。

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

base = Blueprint('main', __name__)

@base.route('/', defaults={'page':'home'})
@base.route('/<page>')
def show(page):
    try:
        return render_template('%s.html'%page, name='my name is')
    except TemplateNotFound:
        abort(404)

以上是我的蓝图文件,这些路线工作正常,但如果我尝试这样做

with flask.test_request_context():
    print url_for('home') #home.html or any other forms

我只是得到这个错误:

raise BuildError(endpoint, values, method)
werkzeug.routing.BuildError: ('home', {}, None)

谁能帮我弄清楚这里发生了什么? 在我的 html 页面中,我可以打印出静态文件的位置:

{{ url_for('static', filename='style.css') }}

但如果我尝试这样做:

{{ url_for('home') }}

我再次遇到同样的错误。有人对如何进行有一些建议吗?

【问题讨论】:

    标签: python werkzeug url-for


    【解决方案1】:

    我想你是在错误地使用url_forurl_for 通常将端点(即 python 函数/方法)映射到 url。在您的情况下,home 是参数的值,而不是端点。

    因此,请改用您想要其 url 的 python 函数的名称:

    url_for('show', page='home')
    

    应该是你要找的。​​p>

    【讨论】:

    • 感谢您提供非常清晰的解释和扩展示例。
    【解决方案2】:

    当您执行{{ url_for('home') }} 时,它不会返回 home.html 的路由,而是返回函数home 的路由,顺便说一句,它不存在。

    所以要解决您的问题, 使用url_for 的正确方法是:

    {{ url_for('show') }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      相关资源
      最近更新 更多