python---tornado钩子预留解析

在tornado.web.RequestHandler类中的初始构造方法中:

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)
View Code

尾部自动调用tornado为用户预留的initialize方法(未实现,是由用户调用来实现)

    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
View Code

所以对于之前的session类的使用上可以用到钩子,就像php中的公共控制类中构造方法中调用某些函数,会在每个控制器执行时去执行这些函数,减少在代码中的复用。

前面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("请登录")

 

转载于:https://www.cnblogs.com/ssyfj/p/8529267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值