在tornado.web.RequestHandler類中的初始構造方法中:php
class RequestHandler(object): """Base class for HTTP request handlers. Subclasses must define at least one of the methods defined in the "Entry points" section below. """ SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS") _template_loaders = {} # type: typing.Dict[str, template.BaseLoader] _template_loader_lock = threading.Lock() _remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]") def __init__(self, application, request, **kwargs): super(RequestHandler, self).__init__() self.application = application self.request = request self._headers_written = False self._finished = False self._auto_finish = True self._transforms = None # will be set in _execute self._prepared_future = None self._headers = None # type: httputil.HTTPHeaders self.path_args = None self.path_kwargs = None self.ui = ObjectDict((n, self._ui_method(m)) for n, m in application.ui_methods.items()) # UIModules are available as both `modules` and `_tt_modules` in the # template namespace. Historically only `modules` was available # but could be clobbered by user additions to the namespace. # The template {% module %} directive looks in `_tt_modules` to avoid # possible conflicts. self.ui["_tt_modules"] = _UIModuleNamespace(self, application.ui_modules) self.ui["modules"] = self.ui["_tt_modules"] self.clear() self.request.connection.set_close_callback(self.on_connection_close) self.initialize(**kwargs)
尾部自動調用tornado爲用戶預留的initialize方法(未實現,是由用戶調用來實現)web
def initialize(self): """Hook for subclass initialization. Called for each request. A dictionary passed as the third argument of a url spec will be supplied as keyword arguments to initialize(). Example:: class ProfileHandler(RequestHandler): def initialize(self, database): self.database = database def get(self, username): ... app = Application([ (r'/user/(.*)', ProfileHandler, dict(database=database)), ]) """ pass
因此對於以前的session類的使用上能夠用到鉤子,就像php中的公共控制類中構造方法中調用某些函數,會在每一個控制器執行時去執行這些函數,減小在代碼中的複用。cookie
前面session類的改進session
class BaseRequestHandler(tornado.web.RequestHandler): #tornado預留鉤子函數 def initialize(self): self.session=Session(self) class IndexHandler(BaseRequestHandler): def get(self): if self.get_argument('u',None) in ['asd','zxc']: #在這裏有個bug,當程序兩次設置值時,邏輯相同,可是因爲只發送了一次請求,獲取了第一次的py_session #在相同邏輯代碼處理下random_str=self.handler.get_cookie('py_session') #每次都是不正確的,都須要從新建立一個標識符 #可是後面的刷新過程當中因爲修改了客戶區的py_session,因此能夠正常進行操做,可是第一次產生的py_session的依舊存在服務端 self.session.set_value('is_login',True) self.session.set_value('name',self.get_argument('u')) #self.get_secure_cookie() #The decoded cookie value is returned as a byte string (unlike #`get_cookie`). else: self.write("請登陸")