代码好久没写了 手感很生疏
接上一篇的文章 登录和注册都有了 那么肯定还有注销
代码如下
@bp.route('/logout/', methods=['GET'])
@is_login
def logout():
if request.method == 'GET':
session.clear()
return redirect(url_for('user.login'))
代码写的很简洁 注销了就把session清空 然后我就让你去跳登录
看一下@is_login这个方法是自己写的装饰器 用来判断是否登录 你没有登录当然不可能有注销
那么 这个is_login是怎么来的呢
代码如下
def is_login(func):
@wraps(func)
def check_login(*args, **kwargs):
user_id = session.get('user_id')
if user_id:
return func(*args, **kwargs)
else:
return redirect(url_for('user.login'))
return check_login
在is_login这个方法里面 我又加了个check_login方法检查是否登录
获取到session里面的user_id 如果有那我就可以走后面代码的逻辑了
如果没有那么我只好去跳登录
最后我们来看一下前端代码
我把注销的前端代码放在了head.html 把整个前端登录成功后显示的页面做了分割 感觉会更清晰一点
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>头部</title>
<link rel="stylesheet" type="text/css" href="/static/css/public.css" />
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/public.js"></script>
</head>
<body>
<!-- 头部 -->
<div class="head">
<div class="headl" >
<img class="headLogo" src="/static/img/logLOGO.png"/>
</div>
<div class="headR">
<span style="color:#FFF">欢迎:{{username}}</span> <a href="{{ url_for('user.logout') }}" target="_top">【退出】</a>
</div>
</div>
</body>
</html>