I wrote before the session is generally stored in the server's memory, which can be stored in the cache, or the database, the problem comes, different places, save the way is different, so need to define different classes,cache/redis/memcached class
session.py
ImportConfig fromHashlibImportSHA1ImportOSImportTime create_session_id=Lambda: SHA1 (Bytes ('%s%s'% (Os.urandom (+), Time.time ()), encoding='Utf-8') . Hexdigest ()classCachesession:session_container={} session_id="__sessionid__" def __init__(self, handler): Self.handler=handler Client_random_str=Handler.get_cookie (cachesession.session_id, None)ifClient_random_str andClient_random_strinchCacheSession.session_container:self.random_str=Client_random_strElse: Self.random_str=create_session_id () cachesession.session_container[self.random_str]={} expires_time= Time.time () +CONFIG. Session_expires Handler.set_cookie (cachesession.session_id, self.random_str, EXPIRES=expires_time)def __getitem__(self, key): Ret=cachesession.session_container[self.random_str].get (Key, None)returnretdef __setitem__(self, Key, value): Cachesession.session_container[self.random_str][key]=valuedef __delitem__(self, key):ifKeyinchCachesession.session_container[self.random_str]:delCachesession.session_container[self.random_str][key]classredissession:def __init__(self, handler):Pass classmemcachedsession:def __init__(self, handler):Pass
Write the session to death, if you change the session type, you need to spend a lot of effort to modify, so lead today to say factory method mode, in session file again define a Sessionfactory class
classsessionfactory: @staticmethoddefGet_session_obj (handler): obj=NoneifConfig. Session_type = ="Cache": obj=cachesession (handler)elifConfig. Session_type = ="memcached": obj=memcachedsession (handler)elifConfig. Session_type = ="Redis": obj=redissession (handler)returnObj
and write the session type you want to use in the config file, just modify the configuration file each time you modify it.
settings.py
# session Type: cache/redis/memcached " Cache " # Session time-out (seconds) Session_expires = 60 * 20
In tornado, the RequestHandler class provides a initialize method for executing before an instance handler an object, and we create a session object in this method. and assign to the handler object self.session this normal field
request_handler.py
Import Tornado.web from Import sessionfactory class Baserequesthandler (Tornado.web.RequestHandler): def Initialize (self): = Sessionfactory.get_session_obj (self)
Execution Process:
The front-end access Url--> routing system corresponds to handler class---Execute Initialize Method (create self.session normal field)--session.py static method Sessionfactory Session_obj--> instantiates the session object based on the given value of the configuration file and return
Code explanation
fromHashlibImportSHA1ImportOSImport TimeImportConfig#construct a function to generate session random field stringcreate_session_id =Lambda: SHA1 (Bytes ('%s%s'% (Os.urandom (+), Time.time ()), encoding='Utf-8') . Hexdigest ()classsessionfactory:#static methods are called directly by the class@staticmethoddefGet_session_obj (handler): obj=NoneifConfig. Session_type = ="Cache": obj=cachesession (handler)elifConfig. Session_type = ="memcached": obj=memcachedsession (handler)elifConfig. Session_type = ="Redis": obj=redissession (handler)returnobjclasscachesession:#dictionary for storing session key-value pairsSession_container = {} #Specify the front-end storage cookie when keysession_id ="__sessionid__" def __init__(self, handler): Self.handler=Handler#front-end Cookie {"__sessionid__": "Session Random string"}Client_random_str =Handler.get_cookie (cachesession.session_id, None)#If you can get a random string to the session and also in the server memory ifClient_random_str andClient_random_strinchCachesession.session_container:#assign the obtained random string to the Self.random_strSelf.random_str =Client_random_strElse: #No, a random string is generated .Self.random_str =create_session_id ()#background Server {"Session random string": {...}}CACHESESSION.SESSION_CONTAINER[SELF.RANDOM_STR] = {} #Set Expiration TimeExpires_time = Time.time () +CONFIG. Session_expires#and write to the cookieHandler.set_cookie (cachesession.session_id, Self.random_str, expires=expires_time)def __getitem__(self, key):#Self.session[key]RET =cachesession.session_container[self.random_str].get (Key, None)returnretdef __setitem__(self, Key, value):#Self.session[key] = valueCachesession.session_container[self.random_str][key] =valuedef __delitem__(self, key):#del Self.session[key] ifKeyinchCachesession.session_container[self.random_str]:delCachesession.session_container[self.random_str][key]classredissession:def __init__(self, handler):Pass classmemcachedsession:def __init__(self, handler):Pass
Drawer Tornado Combat (6)--session Factory (factory method mode)