Flask 蓝图和登录重定向问题

Mik*_*ton 5 python werkzeug flask

我有一个示例 Flask 应用程序,它基本上可以工作。基本 URL ( /) 不需要身份验证;但是,我在 处有一个资源/auth/secured,需要身份验证。

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

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

我正在使用 Flask Blueprints 进行 URL 路由...我认为这应该可行...

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
Run Code Online (Sandbox Code Playgroud)

app目录构建如下:

testapp/
 |
 + config.py
 + manage.py
 + app/
   |
   + __init__.py
   + auth/
     |
     + __init__.py
     + views.py
   + main/
     |
     + __init__.py
     + views.py
Run Code Online (Sandbox Code Playgroud)

据我所知,我的蓝图注册中出现了一些混乱;但是,我不知道错误在哪里。

/auth/login当未经身份验证的用户以未经身份验证的用户身份上网时,如何使他们正确重定向到URL /auth/secured

two*_*eet 4

看起来有几个问题。

第一个是缺少配置参数LDAP_LOGIN_VIEW. 默认值是,login但由于您没有名为“login”的视图,因此您可能希望将其设置auth.login在配置文件中:

LDAP_LOGIN_VIEW = 'auth.login'
Run Code Online (Sandbox Code Playgroud)

下一个问题是您auth.login不处理下一个参数。下一个参数告诉登录函数在成功登录后重定向到哪里。这可能会导致问题,因为 Flask-simpleldap 正在此处传递下一个参数

return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'], 
       next=request.path))
Run Code Online (Sandbox Code Playgroud)

您可以通过请求对象访问下一个参数。

例子:

from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
Run Code Online (Sandbox Code Playgroud)