首页 > 代码库 > 自定义Session

自定义Session

技术分享
#!/usr/bin/env python
import tornado.ioloop
import tornado.web

container = {}
class Session:
    def __init__(self,handler):
        self.handler = handler
        self.random_str = None

    def __set_random_str(self):
        import hashlib
        import time
        obj = hashlib.md5 ( )
        obj.update ( bytes ( str ( time.time ( ) ), encoding=utf-8 ) )
        random_str = obj.hexdigest ()
        return random_str
    def set_value(self,key,value):
        if not self.random_str:
            random_str = self.handler.get_cookie(__kakaka__)
            if not random_str:
                random_str = self.__set_random_str()
                container[random_str] = {}
            else:
                if random_str in container.keys():
                    pass
                else:
                    random_str = self.__set_random_str()
                    container[random_str] = {}
            self.random_str = random_str
        container[self.random_str][key] = value
        self.handler.set_cookie("__kakaka__",self.random_str)
    def get_value(self,key):
        random_str = self.handler.get_cookie(__kakaka__)
        if not random_str:
            return None
        user_info_dict = container.get(random_str,None)
        if not user_info_dict:
            return None
        value = user_info_dict.get(key,None)
        return value
class IndexHander(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        if self.get_argument(u,None)in[alex,eric]:
            s = Session(self)
            s.set_value(is_login, True)
            s.set_value(name, self.get_argument(u,None))
            print(container)
        else:
            self.write(请登录)
class ManagerHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        s = Session(self)
        val = s.get_value(is_login)
        if val:
            self.write(s.get_value(name))
        else:
            self.write("失败")

settings = {
    "template_path":"views",
    "static_path":"statics",
    "cookie_secret":"taochen"
}

application = tornado.web.Application([
    (r"/index",IndexHander),
    (r"/manager",ManagerHandler),
],**settings)

if __name__ == __main__:
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
app.py
技术分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <div>首页</div>
</body>
</html>
index.html

 

自定义Session