Flask蓝图和登录重定向问题

时间:2016-05-08 20:43:46

标签: python flask werkzeug

我有一个sample Flask app,大部分都有效。基本网址(/)不需要身份验证;但是,我有/auth/secured的资源,需要进行身份验证。

只要用户登录,该应用就可以正常运行;但是,当有人试图以未经身份验证的用户身份访问werkzeug.routing.BuildError (BuildError: Could not build url for endpoint 'login' with values ['next']. Did you mean 'auth.login' instead?)时,它会抛出 /auth/secured ,因为我的代码是这样的:

@auth.route('/secured')
@ldap.login_required
def secured():
    return 'Login Success! {0}'.format(session)

我正在使用Flask蓝图进行网址路由......我认为这应该可行...

def create_app(config_name):
    from .main import main as main_blueprint
    from .auth import auth as auth_blueprint

    # Configure the flask instance...
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Initialize the application...
    bootstrap.init_app(app)
    db.init_app(app)
    ldap.init_app(app)

    # Blueprint registration
    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    return app

app目录的构建如下:

testapp/
 |
 + config.py
 + manage.py
 + app/
   |
   + __init__.py
   + auth/
     |
     + __init__.py
     + views.py
   + main/
     |
     + __init__.py
     + views.py

我可以说,我的蓝图注册中有些东西搞砸了;但是,我对错误的位置感到茫然。

如果未经身份验证的用户在作为未经身份验证的用户浏览/auth/login时,如何正确地将其重定向到/auth/secured网址?

1 个答案:

答案 0 :(得分:2)

看起来有几个问题。

第一个是缺少配置参数accordian()The default is login但由于您没有名为“登录”的视图,因此您可能希望在配置文件中将其设置为LDAP_LOGIN_VIEW

auth.login

下一个问题是您的LDAP_LOGIN_VIEW = 'auth.login' 无法处理下一个参数。下一个参数告诉登录功能在成功登录后重定向的位置。这可能会导致问题,因为flask-simpleldap是passing a next parameter here

auth.login

您可以通过request object访问下一个参数。

示例:

return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'], 
       next=request.path))