• global,tornado的write_error,tornado的中间件的写法


    1.global关键字:Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global

    2.python中引用变量,全局变量是可以引用的,但是修改时必须加global关键字

    3.tornado中间件

    实现在线人数统计
    和登陆验证功能

    from tornado.ioloop import IOLoop
    from tornado.web import RequestHandler, Application
    
    
    class MiddleWare(object):
        def process_request(self, handler):
            pass
    
        def process_response(self, handler):
            pass
    
    
    class CheckLogin(MiddleWare):
        def is_login(self, handler):
            pwd = handler.get_argument("pwd", "")
            if not pwd:
                raise Exception("login required")
            # else:
            #     # 判断用户名密码
            #     return
    
        def process_request(self, handler):
            self.is_login(handler)
    
    
    session_counter = 0
    
    
    class Counter(MiddleWare):
        def process_request(self, handler):
            global session_counter
            session_counter = session_counter + 1
    
    
    class MiddleHandler(RequestHandler):
    
        def initialize(self, middleware):
            self.middleware = middleware
    
        def prepare(self):
            # print(self)
            # self 是Echohandler的类的实例化对象
            for middleware in self.middleware:
                middleware.process_request(self)
    
        def finish(self, chunk=None):
            super(MiddleHandler, self).finish(chunk)
    
        def write_error(self, status_code, **kwargs):
            # print(kwargs)#{'exc_info': (<class 'Exception'>, Exception('login required',), <traceback object at 0x0000020307E9CC08>)}
            exc_cls, exc_instance, trace = kwargs.get("exc_info")
            if status_code != 200:
                self.set_status(status_code)
                self.write({"msg": str(exc_instance)})
    
    
    class EchoHandler(MiddleHandler):
        def get(self):
            message = self.get_argument("msg", "world")
    
            self.write("hello, %s, current online: %d" % (message, session_counter))
    
    
    def get_middleware():
        return (CheckLogin(), Counter())
    
    
    import tornado.ioloop
    
    if __name__ == '__main__':
        middleware_list = get_middleware()
        print(middleware_list)
        app = Application([(r"/echo", EchoHandler, dict(middleware=middleware_list))])
        app.listen(8888)
        tornado.ioloop.IOLoop.current().start()
  • 相关阅读:
    HDU 4565 So Easy!(数学+矩阵快速幂)(2013 ACM-ICPC长沙赛区全国邀请赛)
    HDU 4568 Hunter(最短路径+DP)(2013 ACM-ICPC长沙赛区全国邀请赛)
    URAL 1664 Pipeline Transportation(平面图最大流)
    HDU 1250 Hat's Fibonacci(高精度)
    HDU 1042 N!(高精度乘)
    算法模板の计算几何
    算法模板の数据结构
    算法模板の数学&数论
    算法模板之图论
    HDU 3260/POJ 3827 Facer is learning to swim(DP+搜索)(2009 Asia Ningbo Regional)
  • 原文地址:https://www.cnblogs.com/liuer-mihou/p/11484742.html
Copyright © 2020-2023  润新知