Flask-Classy url_for问题(builderror)

时间:2013-02-15 08:51:22

标签: python flask

在访问Flask-Classy视图方法时,我遇到了在我的模板中嵌入url_for(或在我的视图中定义)的麻烦。

/app/routes.py

class BaseView(FlaskView):
    route_base '/'

    @route('index', endpoint('index')
    def index():
        return render_template('index.html')

    def resetapp():
        db.drop_all()
        return redirect(url_for('BaseView:index'))

/app/crm/accounts/routes.py

class AccountView(FlaskView):
    route_base '/crm/account/'

    @route('create', endpoint='create')
    def create():
        return render_template('path/to/create.html')

现在在'index.html'中,我有以下内容

但是我收到以下错误: werkzeug.routing.BuildError

  

BuildError:('AccountView.create',{},None)

如果你看第一条路线,有resetapp使用url_for引用自己作为BaseView:index - 这是有效的!

我也在index.html {{url_for('AccountView:create')}}中尝试了相同的格式但是同样的错误。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您似乎忘了注册视图BaseView.register(app),以下是可行的代码:

from flask import Flask,url_for,redirect,render_template
from flask.ext.classy import FlaskView,route

app = Flask(__name__)

class BaseView(FlaskView):
    route_base= '/'

    @route('index')
    def index(self):
        print url_for('BaseView:index')
        return render_template("index.html")
    @route('reset')
    def reset(self):
        print url_for('BaseView:reset')
        return redirect(url_for('BaseView:index'))
BaseView.register(app)
if __name__ == '__main__':
    app.run(debug=True)

答案 1 :(得分:1)

问题是你在路由装饰器中覆盖了端点,但仍然试图从默认端点访问它们。此外,index特殊方法,如果您希望它映射到FlaskView的根目录,则不需要路径修饰符。 (您还忘记了self参数!)尝试将代码更改为:

class BaseView(FlaskView):
    route_base '/'

    def index(self):
        return render_template('index.html')

    def resetapp(self):
        db.drop_all()
        return redirect(url_for('BaseView:index'))

现在url_for('BaseView:index')将返回"/"

答案 2 :(得分:1)

好的,这需要一段时间 - 但事实证明我带领你进行疯狂的追逐。问题是一个人的建议,但主要问题是与一个有争论的路线...

对于那些想知道如何做到这一点的人。以下是Flask-Classy url_for()

的答案
@route('update/<client_id>', methods=['POST','GET'])
def update(self, client_id=None):

    if client_id is None:
        return redirect(url_for('ClientView:index'))

在你的模板中:

{{ url_for('YourView:update', client_id=some_var_value, _method='GET') }}

以下是您无法做的事情 - 正确使用Flask-Classy。

  1. 设置端点 - 这是禁忌。设置端点后,将覆盖Class:Method routing。
  2. 确保提供正确数量的查询参数。
  3. 如果要使用url_for
  4. ,则无法定义多个路径

    我也特意提供了这种方法 - 但这是不必要的。

    对于第3点 - 这是因为当有超过1条路线时 - 它如何知道使用哪条路线?很简单,但这就是我在圈子里追逐自己的原因。除了删除其他路线外,请执行所有操作。