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()