flask操作session--登陆认证与注销的例子
项目的目录结构如下
特别注意:默认情况下~存放静态文件的目录必须叫“static”,存放项目模板的目录必须叫“templates”~~
后台python代码如下
# -*- coding:utf-8 -*- from flask import Flask,render_template,session,redirect,request app = Flask(__name__) app.debug = True # 为session加密的key app.secret_key = 'huoyingwhw' # session的生存时间——测试时设置 app.permanent_session_lifetime = 1551 # session校验的装饰器函数 def check_login(func): def inner(*args,**kwargs): if session.get('user'): ret = func(*args,**kwargs) return ret else: return redirect('/login') return inner @app.route('/login',methods=['GET','POST'],endpoint='login') def login(): if request.method == 'GET': return render_template('login.html') elif request.method == 'POST': uname = request.form.get('username') pwd = request.form.get('password') if uname == 'whw' and pwd == '123': session['user'] = 'whw' return redirect('/index') else: count = session.get('fail_counts',0) if count: count += 1 session['fail_counts'] = count else: session['fail_counts'] = 1 return '用户名或密码错误,你登陆失败了 %s 次'%(session['fail_counts']) @app.route('/index',endpoint='index') @check_login def index(): return render_template('index.html',stu_dic=STUDENT_DICT) @app.route('/reback',endpoint='reback') @check_login def reback(): return redirect('/login') @app.route('/logout',endpoint='logout',methods=['POST']) @check_login def logout(): # 清空session session.clear() return '666' if __name__ == '__main__': STUDENT_DICT = { 1: {'name': 'www', 'age': 38, 'gender': '中'}, 2: {'name': 'whw', 'age': 73, 'gender': '男'}, 3: {'name': 'naruto', 'age': 84, 'gender': '女'}, } app.run('127.0.0.1','5678')
登陆的前端代码如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆</title> </head> <body> <form action="" method="post"> 用户名<input type="text" name="username"> 密 码<input type="text" name="password"> <button>提交</button> </form> </body> </html>
主页的前端代码如下
注意ajax的写法~~ajax给后台发送了一个post请求~对应的/logout这个路由中的methods列表必须加上post方法~~
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body> <h1>欢迎 {{ session.user }}</h1> <button id="logout">注销</button> <table> <thead> <tr> <td>name</td> <td>age</td> <td>gender</td> </tr> </thead> <tbody> {% for stu in stu_dic.values() %} <tr> <td>{{ stu.name }}</td> <td>{{ stu.age }}</td> <td> {% if stu.gender == '男' or stu.gender == '女' %} {{ stu.gender }} {% else %} 男 {% endif %} </td> </tr> {% endfor %} </tbody> </table> <script src="/static/jquery-3.4.1.js"></script> <script> $('#logout').click(function () { $.ajax({ url:'/logout', type:'post', success:function (data) { //console.log(data); {# 收到666后返回login页面 #} if(data==='666'){ location.href = '/login'; } } }) }) </script> </body> </html>