登录后如何注销

时间:2014-10-29 22:26:10

标签: python flask

我正在使用this Flask代码。到目前为止它的工作正常,但如果我想退出该怎么办呢。我想在我的html代码上有一个按钮,当我注销再次请求auth时。 我怎样才能实现这个代码

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == 'admin' and password == 'secret'

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route("/")
@requires_auth
def index():
    return render_template("welcome.html", uptime=GetUptime())
#Logout function
@app.route('/logout')
def logout():
    #return redirect(url_for('index'))
    flash('You were logged out')
    return authenticate()))

3 个答案:

答案 0 :(得分:1)

您正在使用基本身份验证。它没有“注销”的概念,但是,您可以通过发送错误的凭据(例如,密码无效的用户名)并返回401而不是200来模拟一个。有多种方法可以实现注销,但为了保持简单,您可以呈现模板视图或返回信息性文本,始终使用401作为响应http代码:

@ns.route('/logout')
def logout():
    """End the current user session"""
    return "Your session was closed", 401

答案 1 :(得分:0)

您可以使用auth数据创建会话(无论是否使用基本身份验证),并且当您想要注销时只需删除会话数据。

答案 2 :(得分:0)

如果您使用nice flask-login扩展名,则可以使用logout_user函数

from flask_login import login_user, logout_user

然后只为它创建一个端点(url)

@expose('/logout/')
def logout(self):
    logout_user()
    return redirect(url_for('index')
相关问题