首页 > 代码库 > session之cookie

session之cookie

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

class IndexHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        if self.get_argument(‘u‘,None)in [‘alex‘,‘eric‘]:
            import hashlib
            import time
            # 加密生成随机字符串
            obj = hashlib.md5()
            obj.update(bytes(str(time.time()),encoding=‘utf-8‘))
            random_str = obj.hexdigest()
            print(random_str)
            # 把随机字符串添加到全局字典里面 并且给他设置value
            container[random_str] = {}
            container[random_str][‘k1‘] = 123
            container[random_str][‘k2‘] = self.get_argument(‘u‘,None) + ‘parents‘
            container[random_str][‘is_login‘] = True
            # 把cookie 写到用户浏览器中
            self.set_cookie(‘iiiii‘,random_str)
        else:
            self.write(‘请登录‘)
class  ManagerHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        # 获取用户浏览器上的cookie 随机字符串
        random_str = self.get_cookie(‘iiiii‘)
        current_user_info = container.get(random_str,None)
        # 判断 随机字符串里面的 is_login 值是否为 True
        if current_user_info.get(‘is_login‘,None):
            temp = "%s - %s"%(current_user_info.get(‘k1‘,""),current_user_info.get(‘k2‘,""))
            self.write(temp)
        else:
            self.render(‘/index‘)



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

  

session之cookie