#!/usr/bin/env python# -*- coding:utf-8 -*-import tornado.ioloopimport tornado.webcontainer = {}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 valclass 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('失败')class LoginHandler(BaseHandler): def get(self, *args, **kwargs): self.render('login.html',status = "") def post(self, *args, **kwargs): user = self.get_argument('user',None) pwd = self.get_argument('pwd',None) code = self.get_argument('code',None) ceck_code = self.session['CeckCode'] if ceck_code.upper() == code.upper(): self.write('验证码正确') else: self.render('login.html',status = '验证码错误')class CodeHandler(BaseHandler): def get(self, *args, **kwargs): import io import check_code mstream = io.BytesIO() # 创建图片 并写入验证码 img,code = check_code.create_validate_code() # 为每个用户保存验证码 self.session['CeckCode'] = code # 将图片写入IO mstream 中 img.save(mstream,"GIF") # 发送图片到客户端 self.write(mstream.getvalue()) passclass XsrfHandler(BaseHandler): def get(self, *args, **kwargs): self.render('csrf.html') def post(self, *args, **kwargs): self.write('Hello')settings = { 'template_path':'views', 'static_path':'statics', 'cookie_secret':'skjfsajdklfjalskj', # 开启POST提交 xsrf 验证 需要HTML表单中携带 {% raw xsrf_form_html() %} 才能提交 'xsrf_cookies':True,}application = tornado.web.Application([ (r"/index",IndexHandler), (r"/manager",ManagerHandler), (r"/login",LoginHandler), (r"/check_code",CodeHandler), (r"/csrf",XsrfHandler),],**settings)if __name__ == '__main__': application.listen(8888) tornado.ioloop.IOLoop.instance().start()