微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐