1.global關鍵字:Python中定義函數時,若想在函數內部對函數外的變量進行操做,就須要在函數內部聲明其爲globalpython
2.python中引用變量,全局變量是能夠引用的,可是修改時必須加global關鍵字web
3.tornado中間件session
實如今線人數統計
和登錄驗證功能app
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()