cookie的设置和获取
1 import time 2 from tornado.web import RequestHandler 3 4 5 class IndexHandle(RequestHandler): 6 def get(self): 7 # 设置cookie 8 self.set_cookie(‘username‘, ‘ivy‘) 9 # 设置过期时间为60s 10 self.set_cookie(‘username‘, ‘ivy‘, expires=time.time() + 60) 11 # 设置过期时间为2天 12 self.set_cookie(‘username‘, ‘ivy‘, expires_days=2) 13 # 当httponly为True时,网页的js代码无法获取该cookie 14 self.set_cookie(‘username‘, ‘ivy‘, httponly=True) 15 # 设置cookie的过期时间为2分钟,max_age的优先级大于expires 16 self.set_cookie(‘username‘, ‘ivy‘, max_age=120, expires=time.time() + 60) 17 # 设置加密的cookie,设置加密必须到app的里面去新增一个cookie_secret的参数,让这个参数等于一个字符串(盐) 18 self.set_secure_cookie(‘username‘, ‘ivy‘) 19 20 21 # 获取cookie 22 self.get_cookie(‘ivy‘) 23 # 获取加密的cookie, 返回字节数据 24 self.get_secure_cookie(‘username‘)
登录验证
1 from tornado.web import RequestHandler, Application, authenticated 2 from tornado.httpserver import HTTPServer 3 from tornado.options import options, define 4 from tornado.ioloop import IOLoop 5 from util import uimethods, uimodules 6 7 define(‘port‘, default=7981, type=int) 8 9 10 class BaseHandle(RequestHandler): 11 def get_current_user(self): 12 current_user = self.get_secure_cookie(‘username‘) 13 if current_user: 14 return current_user 15 return None 16 17 18 class IndexHandle(BaseHandle): 19 @authenticated 20 def get(self): 21 self.render(‘index.html‘) 22 23 24 class LoginHandle(RequestHandler): 25 def get(self): 26 self.render(‘login.html‘) 27 28 def post(self): 29 username = self.get_argument(‘username‘) 30 password = self.get_argument(‘password‘) 31 if username == password: 32 self.set_cookie(username, password) 33 self.write(‘登录成功!‘) 34 35 36 application = Application( 37 handlers=[ 38 (r‘/index‘, IndexHandle), 39 (r‘/login‘, LoginHandle), 40 ], 41 template_path=‘templates‘, 42 ui_methods=uimethods, 43 ui_modules=uimodules, 44 login_url=‘/login‘, 45 ) 46 47 if __name__ == ‘__main__‘: 48 options.parse_command_line() 49 app = HTTPServer(application) 50 app.listen(options.port) 51 IOLoop.current().start()
原文:https://www.cnblogs.com/ivy-blogs/p/10838415.html