from flask import Flask, views, render_template, request, session, redirect
import redis as redis #pip install redis
from flask_session import Session#pip install Flask-session app = Flask(__name__) #使用第三方组件Flask-session就不需要设置secret_key
# app.secret_key = 'wertyui234567gf!@#$%^&*(' app.config['SESSION_TYPE']='redis'#配置数据库类型
app.config['SESSION_REDIS']=redis.Redis(host='127.0.0.1',port=6379,db=6)#连接数据库,db为redis数据库的分区,一共有0-15(默认为0)16个区
Session(app)#自定义启用当前Flask实例session配置 class Login(views.MethodView):
def get(self):
print(request.cookies)
return render_template('login.html') def post(self):
username = request.form.get('username')
pwd = request.form.get('pwd')
if username == 'yang' and pwd == '':
session['username'] = 'yang'#直接再使用session,生成随机字符串sessionid,
# 拼接SESSION_COOKIE_NAME+':'+seesionid得到一个字符串充当reids数据库中的key,
#通过pickle序列化key得到val,以key:val存在redis中,
#同时写入cookie返回给客户端cookie:{SESSION_COOKIE_NAME:sessionid} return redirect('/index')
else:
return '账号或密码有误!!!!' def index():
if session.get('username'): return 'index'
else:
return redirect('/login') app.add_url_rule('/login', view_func=Login.as_view(name='login'))
app.add_url_rule('/index',view_func=index)
if __name__ == '__main__':
app.run()