标签:
后台设置
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): print(self.cookies) print(self.get_cookie(‘k1‘)) self.set_cookie(‘k2‘, ‘999‘) self.render(‘index.html‘) settings = { ‘template_path‘:‘views‘, } application = tornado.web.Application([ (r"/index", MainHandler), ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
前端设置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function setCookieBySeconds(name, value, expires) { var current_date = new Date(); current_date.setDate(current_date.getSeconds()+expires); document.cookie = name + ‘= ‘ + value +‘;expires=‘ + current_date.toUTCString(); } function setCookieByDays(name, value, expires) { var current_date = new Date(); current_date.setDate(current_date.getDate()+expires); document.cookie = name + ‘= ‘ + value +‘;expires=‘ + current_date.toUTCString(); } //此外还可以导入jquery.cookie.js后通过 // $.cookie(‘k1‘,‘v1‘,{expires:7});设置过期时间为7天 </script> </body> </html>
cookie很容易被恶意的客户端伪造,加入你想在cookie中保存当前登陆用户的id之类的信息,你需要对cookie做签名以防止伪造,Tornado通过set_secure_cookie和get_secure_cookie方法直接支持了这种功能,要使用这些方法,你需要在创建应用一个密钥,名字为cookie_secret(在settings配置cookie_secret)
签名Cookie的本质是:
写cookie过程:
- 将值进行base64加密
- 对除值以外的内容进行签名,哈希算法(无法逆向解析)
- 拼接 签名 + 加密值
读cookie过程:
- 读取 签名 + 加密值
- 对签名进行验证
- base64解密,获取值内容
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): login_user = self.get_secure_cookie("login_user", None) if login_user: self.write(login_user) else: self.redirect(‘/login‘) class LoginHandler(tornado.web.RequestHandler): def get(self): self.current_user() self.render(‘login.html‘, **{‘status‘: ‘‘}) def post(self, *args, **kwargs): username = self.get_argument(‘name‘) password = self.get_argument(‘pwd‘) if username == ‘wupeiqi‘ and password == ‘123‘: self.set_secure_cookie(‘login_user‘, ‘武沛齐‘) self.redirect(‘/‘) else: self.render(‘login.html‘, **{‘status‘: ‘用户名或密码错误‘}) settings = { ‘template_path‘: ‘template‘, ‘static_path‘: ‘static‘, ‘static_url_prefix‘: ‘/static/‘, ‘cookie_secret‘: ‘aiuasdhflashjdfoiuashdfiuh‘ } application = tornado.web.Application([ (r"/index", MainHandler), (r"/login", LoginHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
class Foo(object): def __getitem__(self, key): print(‘__getitem__‘,key) def __setitem__(self, key, value): print(‘__setitem__‘,key,value) def __delitem__(self, key): print(‘__delitem__‘,key) obj = Foo() result = obj[‘k1‘] #obj[‘k2‘] = ‘wupeiqi‘ #del obj[‘k1‘]
class BaseHandler(tornado.web.RequestHandler): def initialize(self): self.xxoo = "wupeiqi" class MainHandler(BaseHandler): def get(self): print(self.xxoo) self.write(‘index‘) class IndexHandler(BaseHandler): def get(self): print(self.xxoo) self.write(‘index‘)
import tornado.ioloop import tornado.web from hashlib import sha1 import os, time #将session以全局变量的形式保存 session_container = {} #创建cookie_str随机字符串 的函数 create_session_id = lambda: sha1(‘%s%s‘ % (os.urandom(16), time.time())).hexdigest() class Session(object): #静态字段--session key名 session_id = "__sessionId__" def __init__(self, request): #尝试获取__sessionId__ session_value = request.get_cookie(Session.session_id) if not session_value: #获取失败,就创建随机字符串 self._id = create_session_id() else: #成功---拿值 self._id = session_value #最后设置cookie---"__sessionId__:随机字符串" request.set_cookie(Session.session_id, self._id) def __getitem__(self, key): return session_container[self._id][key] def __setitem__(self, key, value): if session_container.has_key(self._id): session_container[self._id][key] = value else: session_container[self._id] = {key: value} def __delitem__(self, key): del session_container[self._id][key] class BaseHandler(tornado.web.RequestHandler): def initialize(self): # my_session[‘k1‘]访问 __getitem__ 方法 #实例session对象,实现索引访问 self.my_session = Session(self) class MainHandler(BaseHandler): def get(self): print(self.my_session[‘c_user‘]) print(self.my_session[‘c_card‘]) self.write(‘index‘) class LoginHandler(BaseHandler): def get(self): self.render(‘login.html‘, **{‘status‘: ‘‘}) def post(self, *args, **kwargs): username = self.get_argument(‘name‘) password = self.get_argument(‘pwd‘) if username == ‘wupeiqi‘ and password == ‘123‘: self.my_session[‘c_user‘] = ‘wupeiqi‘ self.my_session[‘c_card‘] = ‘12312312309823012‘ self.redirect(‘/index‘) else: self.render(‘login.html‘, **{‘status‘: ‘用户名或密码错误‘}) settings = { ‘template_path‘: ‘views‘, ‘static_path‘: ‘static‘, ‘static_url_prefix‘: ‘/static/‘, ‘cookie_secret‘: ‘aiuasdhflashjdfoiuashdfiuh‘, ‘login_url‘: ‘/login‘ } application = tornado.web.Application([ (r"/index", MainHandler), (r"/login", LoginHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
标签:
原文地址:http://www.cnblogs.com/xinsiwei18/p/5836381.html