session之cookie封装终极版本

class Foo:
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        pass

    def __getitem__(self, item):
        print(item)
        pass

    def __setitem__(self, key, value):
        print(key,value)
        pass

    def __delitem__(self, key):
        pass

# 调用__int__方法
Foo()

# 调用__call__方法
obj = Foo()
obj()

#调用__getitem__方法
obj = Foo()
obj['k1']

#调用__setitem__方法
obj = Foo()
obj['k1'] = 123

#__delitem__
obj = Foo()
del obj['k1']

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web
container = {}

class Session:

    def __init__(self,handler):
        self.handler = handler
        self.random_str = None
    # 生成随机字符串
    def __random_star(self):
        import hashlib
        import time
        obj = hashlib.md5()
        obj.update(bytes(str(time.time()),encoding='utf-8'))
        random_str = obj.hexdigest()
        return random_str

    # 在用户浏览器上设置cookie
    def __setitem__(self,key,value):
        if not self.random_str:
            # 获取用户上的cookie
            random_str = self.handler.get_cookie('__kakaka__')
            # 如果用户没有 cookie 那么就创建一份
            if not random_str:
                random_str = self.__random_star()
                container[random_str] = {}
            # 如果有
            else:
                # 如果 random_str 在 container.keys()里面 就pass
                if random_str in container.keys():
                    pass
                # 否则 就重新创建一份
                else:
                    random_str = self.__random_star()
                    container[random_str] = {}
            self.random_str = random_str
        container[self.random_str][key] = value
        self.handler.set_cookie('__kakaka__',self.random_str)

    # 获取用户浏览器上的cookie
    def __getitem__(self,key):

        random_str = self.handler.get_cookie('__kakaka__')
        #判断random_str是否为空
        if not random_str:
            return None
        # 到container里面获取下random_str 看是否存在
        user_info_dict = container.get(random_str,None)
        if not user_info_dict:
            return None
        val = user_info_dict.get(key)
        return val

class BaseHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.session = Session(self)

class IndexHandler(BaseHandler):
    def get(self, *args, **kwargs):
        # 获取用户传入的值 如果等于将执行操作
        if self.get_argument('u',None)in ['alex','eric']:

            self.session['is_login'] = True
            self.session['name']= self.get_argument('u',None)


        else:
            self.write('请登录')


class  ManagerHandler(BaseHandler):
    def get(self, *args, **kwargs):
        # 获取用户随机字符串 判断是否是true

        val = self.session['is_login']
        if val:
            self.write(self.session['name'])
        else:
            self.write('失败')



settings = {
    'template_path':'views',
    'static_path':'statics',
    'cookie_secret':'skjfsajdklfjalskj'
}

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

if __name__ == '__main__':
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

  

posted @ 2017-02-07 18:31  200ML  阅读(313)  评论(0编辑  收藏  举报