使用 add_url_rule 时 Flask Blueprint url_for BuildError

Flask Blueprint url_for BuildError when using add_url_rule

当我尝试以 add_url_rule

的方式使用烧瓶蓝图时,我卡在了蓝图中

这是我的烧瓶项目结构:

myapp
... __init__.py
... app.py
... model
... static
... views
...... main.py
... templates
...... base.html
...... results.html

在main.py,这是我的代码:

from flask import Flask, url_for, Blueprint
main_bp = Blueprint('main', __name__)

def home():
    return redirect(url_for('main.results'))

def results():
    # some code
    return render_template('result.html')

在我的 app.py 中,代码如下:

from myapp.views.main import main_bp

app.register_blueprint(main_bp)

app.add_url_rule('/', view_func=main.home)

app.add_url_rule('/results', view_func=main.results, methods=['POST', 'GET'])

当我访问索引页时,总是收到以下错误消息:

Traceback (most recent call last):
File "/Users/deamon/venv/src/staticngclient/staticng_client/middlewares/wsgi.py", line 25, in __call__
return app(environ, start_response)
File "/Users/deamon/venv/src/daeprofiling/dae_profiling/middleware.py", line 24, in __call__
  return self.app(environ, start_response)
File "/Users/deamon/venv/src/doubancommonlib/douban/common/middleware/content_filter.py", line 18, in __call__
  app_iter = self.application(environ, response.start_response)
File "/Users/deamon/dae/app/web.py", line 77, in __call__
  return handler(environ, start_response)
File "/Users/deamon/Projects/dae/dae/handlers/__init__.py", line 65, in __call__
  return self.app(environ, start_response)
File "/Users/deamon/Projects/dae/dae/handlers/web.py", line 46, in __call__
  return self._app(*a, **kw)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
  return self.wsgi_app(environ, start_response)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
  response = self.make_response(self.handle_exception(e))
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
  reraise(exc_type, exc_value, tb)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
  response = self.full_dispatch_request()
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
  rv = self.handle_user_exception(e)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
  reraise(exc_type, exc_value, tb)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
  rv = self.dispatch_request()
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
  return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/deamon/kiwi/views/main.py", line 19, in home
  return redirect(url_for('main.results'))
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for
  return appctx.app.handle_url_build_error(error, endpoint, values)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
  reraise(exc_type, exc_value, tb)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
  force_external=external)
File "/Users/deamon/venv/lib/python2.7/site-packages/werkzeug/routing.py", line 1678, in build
  raise BuildError(endpoint, values, method)
BuildError: ('main.results', {}, None)

另外,在我的模板中,例如 base.html 或 results.html,当我使用

        <a class="navbar-brand" href="{{ url_for('main.home') }}">kiwi</a>

出现同样的错误。

有人可以帮忙吗?

好的,所以我看到的第一个问题是,即使您尝试使用蓝图,您实际上并没有对它做任何事情。

是的,您在 main_bp = Blueprint('main', __name__) 行中创建了它,但之后您实际上并未为其注册任何 url 端点,而是尝试通过主应用程序中的导入来完成。

因为您实际上并没有在蓝图中注册端点,而是尝试通过调用带有蓝图前缀main.results的'main'为其创建重定向] 你的 url_for 函数失败了。

这是您的代码在正确使用蓝图后的样子

蓝图

from flask import Flask, url_for, Blueprint
main_bp = Blueprint('main', __name__)

@main_bp.route('/') 
def home():
    return redirect(url_for('main.results'))

@main_bp.route('/results') 
def results():
    # some code
    return render_template('result.html')

和app.py

from myapp.views.main import main_bp

app.register_blueprint(main_bp)

或者,如果你想使用 add_url_rule(它 与装饰器完全一样 ),只需在蓝图文件中使用 main_bp.add_url_rule(...)

add_url_rule

的工作示例

蓝图文件

from flask import Flask, url_for, Blueprint, redirect, render_template
main_bp = Blueprint('main', __name__)

def home():
    return redirect(url_for('main.results'))

def results():
    # some code
    return 'some results'

main_bp.add_url_rule('/', view_func=home)
main_bp.add_url_rule('/results', view_func=results)

应用文件

from flask import Flask
import bp

app = Flask(__name__)


app.register_blueprint(bp.main_bp)



if __name__ == '__main__':
    app.run()