flask session
1. Flask自带的session功能
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
from flask import session import json app=Flask(__name__,template_folder='templates',static_path='/static/',static_url_path='/static/') app.debug=True app.secret_key='sjehfjeefrjewth43u' #设置session加密 app.config['JSON_AS_ASCII']=False #指定json编码格式 如果为False 就不使用ascii编码, app.config['JSONIFY_MIMETYPE'] ="application/json;charset=utf-8" #指定浏览器渲染的文件类型,和解码格式; @app.route('/login/',methods=['GET','POST']) def login(): msg = '' if request.method=='POST': name=request.values.get('user') pwd=request.values.get('pwd') if name =='zhanggen' and pwd=='123.com': session['user']=name #设置session的key value return redirect('/index/') else: msg='用户名或者密码错误' return render_template('login.html',msg=msg) @app.route('/index/',methods=['GET','POST']) def index(): user_list = ['张根', 'egon', 'eric'] user=session.get('user') #获取session if user: user=['alex','egon','eric'] return jsonify(user_list) else: return redirect('/login/') if __name__ == '__main__': app.run()
2.第三方session组件(Session)
安装 pip install flask-session
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
from flask import session, Flask,request,make_response,render_template,redirect,jsonify,Response from flask.ext.session import Session #引入第三方session import json app=Flask(__name__,template_folder='templates',static_path='/static/',static_url_path='/static/') app.debug=True app.secret_key='sjehfjeefrjewth43u' #设置session加密 app.config['JSON_AS_ASCII']=False #指定json编码格式 如果为False 就不使用ascii编码, app.config['JSONIFY_MIMETYPE'] ="application/json;charset=utf-8" #指定浏览器渲染的文件类型,和解码格式; app.config['SESSION_TYPE']='redis' from redis import Redis #引入连接 redis模块 app.config['SESSION_REDIS']=Redis(host='192.168.0.94',port=6379) #连接redis Session(app) @app.route('/login/',methods=['GET','POST']) def login(): msg = '' if request.method=='POST': name=request.values.get('user') pwd=request.values.get('pwd') if name =='zhanggen' and pwd=='123.com': session['user']=name #设置session的key value return redirect('/index/') else: msg='用户名或者密码错误' return render_template('login.html',msg=msg) @app.route('/index/',methods=['GET','POST']) def index(): user_list = ['张根', 'egon', 'eric'] user=session.get('user') #获取session if user: user=['alex','egon','eric'] return jsonify(user_list) else: return redirect('/login/') if __name__ == '__main__': app.run()
不仅可以把session存放到redis还可放到文件、内存、memcache...
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
def _get_interface(self, app): config = app.config.copy() config.setdefault('SESSION_TYPE', 'null') config.setdefault('SESSION_PERMANENT', True) config.setdefault('SESSION_USE_SIGNER', False) config.setdefault('SESSION_KEY_PREFIX', 'session:') config.setdefault('SESSION_REDIS', None) config.setdefault('SESSION_MEMCACHED', None) config.setdefault('SESSION_FILE_DIR', os.path.join(os.getcwd(), 'flask_session')) config.setdefault('SESSION_FILE_THRESHOLD', 500) config.setdefault('SESSION_FILE_MODE', 384) config.setdefault('SESSION_MONGODB', None) config.setdefault('SESSION_MONGODB_DB', 'flask_session') config.setdefault('SESSION_MONGODB_COLLECT', 'sessions') config.setdefault('SESSION_SQLALCHEMY', None) config.setdefault('SESSION_SQLALCHEMY_TABLE', 'sessions') if config['SESSION_TYPE'] == 'redis': session_interface = RedisSessionInterface( config['SESSION_REDIS'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'memcached': session_interface = MemcachedSessionInterface( config['SESSION_MEMCACHED'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'filesystem': session_interface = FileSystemSessionInterface( config['SESSION_FILE_DIR'], config['SESSION_FILE_THRESHOLD'], config['SESSION_FILE_MODE'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'mongodb': session_interface = MongoDBSessionInterface( config['SESSION_MONGODB'], config['SESSION_MONGODB_DB'], config['SESSION_MONGODB_COLLECT'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'sqlalchemy': session_interface = SqlAlchemySessionInterface( app, config['SESSION_SQLALCHEMY'], config['SESSION_SQLALCHEMY_TABLE'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) else: session_interface = NullSessionInterface() return session_interface
3.自定义session组件
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- import uuid import json from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = {} def __init__(self): import redis self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-session', key_derivation='hmac') def open_session(self, app, request): """ 程序刚启动时执行,需要返回一个session对象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在内存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序结束前执行,可以保存session中所有的值 如: 保存到resit 写入到用户cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在内存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
from flask import Flask from flask import session from my_session import MySessionInterface app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.session_interface = MySessionInterface() @app.route('/login/', methods=['GET', "POST"]) def login(): print(session) session['user1'] = 'alex' session['user2'] = 'alex' del session['user2'] return "内容" if __name__ == '__main__': app.run()
posted on 2018-10-24 15:31 ExplorerMan 阅读(161) 评论(0) 编辑 收藏 举报