本文主要是介绍Flask---session源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我在Flask—上下文源码分析这篇笔记中,简单分析了下Flask的上下文管理源码分析,今天我单拎出来session来,并且结合flask-session
保存到redis
进行分析,先抛出一张图
当我们在项目中构造app = Flask(__name__)
实例时,在发起request请求时,会执行app的__call__
方法
def __call__(self, environ, start_response):"""Shortcut for :attr:`wsgi_app`."""return self.wsgi_app(environ, start_response)
跟踪方法wsgi_app
参看如下代码
ctx = self.request_context(environ)
在RequestContext(self, environ)
中封装了session
def __init__(self, app, environ, request=None):self.app = appif request is None:request = app.request_class(environ)self.request = requestself.url_adapter = app.create_url_adapter(self.request)self.flashes = Noneself.session = None、、、省略部分代码、、、
然后继续回到wsgi_app
方法中,在ctx = self.request_context(environ)
中封装了session
属性之后,在下一行代码中
ctx.push()
进行了如下操作
self.session = self.app.open_session(self.request)
继而跟踪到class SecureCookieSessionInterface(SessionInterface)
类的如下代码
def open_session(self, app, request):s = self.get_signing_serializer(app)if s is None:return Noneval = request.cookies.get(app.session_cookie_name)if not val:return self.session_class()max_age = total_seconds(app.permanent_session_lifetime)try:data = s.loads(val, max_age=max_age)return self.session_class(data)except BadSignature:return self.session_class()
上述代码中通过get_signing_serializer
拿到序列化器,通过val = request.cookies.get(app.session_cookie_name)
获取浏览器Cookie
的session
键对应的值,然后通过data = s.loads(val, max_age=max_age)
获取session数据,以下是数据格式
我们通过如下代码进行设置
session['k1'] = 123session['k2'] = 456
然后如下是输出格式:
val
eyJrMSI6MTIzLCJrMiI6NDU2fQ.DcrHQQ.WGPBpjRyamwNVxWKU7CM_YB8w4
data
{‘k1’: 123, ‘k2’: 456}
浏览器Cookie
的键值对
session=eyJrMSI6MTIzLCJrMiI6NDU2fQ.DcrHQQ.WGPBpjRyamwNVxWKU7CM_YB8w4A
然后在open_session中进行如下操作
return self.session_class(data)
session_class = SecureCookieSession
是构造了一个SecureCookieSession对象,跟踪代码如下
class SecureCookieSession(CallbackDict, SessionMixin):"""Base class for sessions based on signed cookies."""def __init__(self, initial=None):def on_update(self):self.modified = TrueCallbackDict.__init__(self, initial, on_update)self.modified = False
打印出来这个对象输出如下:<SecureCookieSession {'k1': 123, 'k2': 456}>
以上就是self.session = self.app.open_session(self.request)
的流程
接下来继续看wsgi_app
方法,去看如下代码
response = self.full_dispatch_request()
定位到如下代码
return self.finalize_request(rv)
response = self.process_response(response)
然后在process_response
方法中看看如何进行保存session
的
self.save_session(ctx.session, response)
def save_session(self, session, response):return self.session_interface.save_session(self, session, response)
最后执行如下的方法
def save_session(self, app, session, response):domain = self.get_cookie_domain(app)path = self.get_cookie_path(app)if not session:if session.modified:response.delete_cookie(app.session_cookie_name,domain=domain, path=path)returnif not self.should_set_cookie(app, session):returnhttponly = self.get_cookie_httponly(app)secure = self.get_cookie_secure(app)expires = self.get_expiration_time(app, session)val = self.get_signing_serializer(app).dumps(dict(session))response.set_cookie(app.session_cookie_name, val,expires=expires, httponly=httponly,domain=domain, path=path, secure=secure)
通过not self.should_set_cookie(app, session)
进行判断是不是进行了session.modified
可以修改操作
然后通过后,执行保存
val = self.get_signing_serializer(app).dumps(dict(session))response.set_cookie(app.session_cookie_name, val,expires=expires, httponly=httponly,domain=domain, path=path, secure=secure)
序列化dict(session)
,然后写回set_cookie
即可
以上是flask的session源码部分的分析
接下里我们结合flask-session
,保存redis
进行简单分析
通过pip3 install redis
和pip3 install flask_session
安装
我们通过如下代码进行使用
def create_app():app = Flask(__name__)app.config.from_object('settings.DevelopmentConfig')app.register_blueprint(account.account)app.register_blueprint(home.home)# 将session替换成redis sessionSession(app)return app
在 Session(app)
这句代码中,进行了如下的初始化操作
def __init__(self, app=None):self.app = appif app is not None:self.init_app(app)def init_app(self, app):app.session_interface = self._get_interface(app)
然后在_get_interface
方法中去设置自己的配置
如下是_get_interface方法全部代码
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
看如下这几句代码,我们在项目中配置的
SESSION_TYPE = "redis"
SESSION_REDIS = Redis(host='192.168.0.94', port='6379')
会生成RedisSessionInterface
实例对象,如下是代码
if config['SESSION_TYPE'] == 'redis':session_interface = RedisSessionInterface(config['SESSION_REDIS'], config['SESSION_KEY_PREFIX'],config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT'])
然后flask_session库构造了自己的方法,去open_session
和save_session
def open_session(self, app, request):sid = request.cookies.get(app.session_cookie_name)if not sid:sid = self._generate_sid()return self.session_class(sid=sid, permanent=self.permanent)if self.use_signer:signer = self._get_signer(app)if signer is None:return Nonetry:sid_as_bytes = signer.unsign(sid)sid = sid_as_bytes.decode()except BadSignature:sid = self._generate_sid()return self.session_class(sid=sid, permanent=self.permanent)if not PY2 and not isinstance(sid, text_type):sid = sid.decode('utf-8', 'strict')val = self.redis.get(self.key_prefix + sid)if val is not None:try:data = self.serializer.loads(val)return self.session_class(data, sid=sid)except:return self.session_class(sid=sid, permanent=self.permanent)return self.session_class(sid=sid, permanent=self.permanent)def save_session(self, app, session, response):domain = self.get_cookie_domain(app)path = self.get_cookie_path(app)if not session:if session.modified:self.redis.delete(self.key_prefix + session.sid)response.delete_cookie(app.session_cookie_name,domain=domain, path=path)returnhttponly = self.get_cookie_httponly(app)secure = self.get_cookie_secure(app)expires = self.get_expiration_time(app, session)val = self.serializer.dumps(dict(session))self.redis.setex(name=self.key_prefix + session.sid, value=val,time=total_seconds(app.permanent_session_lifetime))if self.use_signer:session_id = self._get_signer(app).sign(want_bytes(session.sid))else:session_id = session.sidresponse.set_cookie(app.session_cookie_name, session_id,expires=expires, httponly=httponly,domain=domain, path=path, secure=secure)
这篇关于Flask---session源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!