声明:本篇来自海燕的博客
除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。
设置:session['username'] = 'xxx'
删除:session.pop('username', None)
from flask import Flask,url_for,session app = Flask(__name__) app.secret_key = "sdsfdgdgdgd" app.config['SESSION_COOKIE_NAME'] = 'session_lvning' #设置session的名字 @app.route('/index/') def index(nid): #session本质上操作的是字典, session是否还有其他方法?与字典方法相同 #session的原理:如果下一次访问的时候带着随机字符串,会把session里面对应的 # 值拿到内存,假设session保存在数据库,每执行一次链接一次数据库,每次都要时时更新的话 # 会非常损耗内存 session["xxx"] = 123 session["xxx2"] = 123 session["xxx3"] = 123 session["xxx4"] = 123 del session["xxx2"] #在这删除了,真正存储的时候是没有xxx2的 return "ddsf" if __name__ == '__main__': app.run()
关于session的配置
app.config['SESSION_COOKIE_NAME'] = 'session_lvning'
- session超时时间如何设置? 'PERMANENT_SESSION_LIFETIME': timedelta(days=31) 以下是跟session相关的配置文件 """ 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, #是否每次都跟新 'PERMANENT_SESSION_LIFETIME': timedelta(days=31)
1 from flask import Flask, session, redirect, url_for, escape, request 2 3 app = Flask(__name__) 4 5 @app.route('/') 6 def index(): 7 if 'username' in session: 8 return 'Logged in as %s' % escape(session['username']) 9 return 'You are not logged in' 10 11 @app.route('/login', methods=['GET', 'POST']) 12 def login(): 13 if request.method == 'POST': 14 session['username'] = request.form['username'] 15 return redirect(url_for('index')) 16 return ''' 17 <form action="" method="post"> 18 <p><input type=text name=username> 19 <p><input type=submit value=Login> 20 </form> 21 ''' 22 23 @app.route('/logout') 24 def logout(): 25 # remove the username from the session if it's there 26 session.pop('username', None) 27 return redirect(url_for('index')) 28 29 # set the secret key. keep this really secret: 30 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
1 pip3 install Flask-Session 2 3 run.py 4 from flask import Flask 5 from flask import session 6 from pro_flask.utils.session import MySessionInterface 7 app = Flask(__name__) 8 9 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' 10 app.session_interface = MySessionInterface() 11 12 @app.route('/login.html', methods=['GET', "POST"]) 13 def login(): 14 print(session) 15 session['user1'] = 'alex' 16 session['user2'] = 'alex' 17 del session['user2'] 18 19 return "内容" 20 21 if __name__ == '__main__': 22 app.run() 23 24 session.py 25 #!/usr/bin/env python 26 # -*- coding:utf-8 -*- 27 import uuid 28 import json 29 from flask.sessions import SessionInterface 30 from flask.sessions import SessionMixin 31 from itsdangerous import Signer, BadSignature, want_bytes 32 33 34 class MySession(dict, SessionMixin): 35 def __init__(self, initial=None, sid=None): 36 self.sid = sid 37 self.initial = initial 38 super(MySession, self).__init__(initial or ()) 39 40 41 def __setitem__(self, key, value): 42 super(MySession, self).__setitem__(key, value) 43 44 def __getitem__(self, item): 45 return super(MySession, self).__getitem__(item) 46 47 def __delitem__(self, key): 48 super(MySession, self).__delitem__(key) 49 50 51 52 class MySessionInterface(SessionInterface): 53 session_class = MySession 54 container = {} 55 56 def __init__(self): 57 import redis 58 self.redis = redis.Redis() 59 60 def _generate_sid(self): 61 return str(uuid.uuid4()) 62 63 def _get_signer(self, app): 64 if not app.secret_key: 65 return None 66 return Signer(app.secret_key, salt='flask-session', 67 key_derivation='hmac') 68 69 def open_session(self, app, request): 70 """ 71 程序刚启动时执行,需要返回一个session对象 72 """ 73 sid = request.cookies.get(app.session_cookie_name) 74 if not sid: 75 sid = self._generate_sid() 76 return self.session_class(sid=sid) 77 78 signer = self._get_signer(app) 79 try: 80 sid_as_bytes = signer.unsign(sid) 81 sid = sid_as_bytes.decode() 82 except BadSignature: 83 sid = self._generate_sid() 84 return self.session_class(sid=sid) 85 86 # session保存在redis中 87 # val = self.redis.get(sid) 88 # session保存在内存中 89 val = self.container.get(sid) 90 91 if val is not None: 92 try: 93 data = json.loads(val) 94 return self.session_class(data, sid=sid) 95 except: 96 return self.session_class(sid=sid) 97 return self.session_class(sid=sid) 98 99 def save_session(self, app, session, response): 100 """ 101 程序结束前执行,可以保存session中所有的值 102 如: 103 保存到resit 104 写入到用户cookie 105 """ 106 domain = self.get_cookie_domain(app) 107 path = self.get_cookie_path(app) 108 httponly = self.get_cookie_httponly(app) 109 secure = self.get_cookie_secure(app) 110 expires = self.get_expiration_time(app, session) 111 112 val = json.dumps(dict(session)) 113 114 # session保存在redis中 115 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) 116 # session保存在内存中 117 self.container.setdefault(session.sid, val) 118 119 session_id = self._get_signer(app).sign(want_bytes(session.sid)) 120 121 response.set_cookie(app.session_cookie_name, session_id, 122 expires=expires, httponly=httponly, 123 domain=domain, path=path, secure=secure)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 """ 4 pip3 install redis 5 pip3 install flask-session 6 7 """ 8 9 10 from flask import Flask, session, redirect 11 from flask.ext.session import Session 12 13 14 app = Flask(__name__) 15 app.debug = True 16 app.secret_key = 'asdfasdfasd' 17 18 19 app.config['SESSION_TYPE'] = 'redis' 20 from redis import Redis 21 app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379') 22 Session(app) 23 24 25 @app.route('/login') 26 def login(): 27 session['username'] = 'alex' 28 return redirect('/index') 29 30 31 @app.route('/index') 32 def index(): 33 name = session['username'] 34 return name 35 36 37 if __name__ == '__main__': 38 app.run()