cookie本质:在浏览器中保存的键值对,每一次HTTP请求时都携带。

如:tornado中用户登录保持,可以使用设置全局变量的方式,也可以设置cookie实现,

设置cookie的方式有两种:一、tornado后台设置;二、浏览器设置;


一、基于tornado框架的后台cookie设置 :用户注册、登录认证等使用,

(一)原生cookie的使用,可以设置过期时间、过期天数、作用域url、path范围等,

1、设置cookie:

self.set_cookie('auth','1',expires_days = 7 )        #设置有效期7天

self.set_cookie('auth','1',expires = time.time()+10)   #设置10秒钟后过期,需要提前import time,

self.set_cookie('auth','1',expires = time.time())     #设置即时失效

2、获取cookie:

self.get_cookie('auth')    # 获取某一个指定的cookie

self.cookies         # 获取当前全部cookies

(二) 除了原生cookie,tornado还提供带签名的cookie

1、设置cookie:self.set_secure_cookie(),

2、获取cookie:self.get_secure_cookie(),

3、在settings中,设置加盐:"cookie_secret":"jfoijfoiewfierr",其中后面字符串的内容自定义,为加盐内容,

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web

USER_INFO = {}

NEWS_LIST = [
    {'title':'胡蝶在吃薯片','content':'胡蝶不好好吃饭,就喜欢吃零食'},
    {'title':'王冬雪在减肥','content':'王冬雪不想吃主食了,太长肉了,她想瘦成闪电'},
]

# 访问首页
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        COOKIE = self.get_cookie('auth')  # 获取cookie,判断是否已登录
        self.render('index.html',userList = USER_INFO,newsList = NEWS_LIST,cookie=COOKIE,)

# 获得登录用户的信息,身份认证
class LoginHandler(tornado.web.RequestHandler):
    def post(self, *args, **kwargs):
        import time  # 设置cookie过期时间
        USER_INFO['name'] = self.get_argument('user',None)
        USER_INFO['pwd'] = self.get_argument('pwd',None)
        if USER_INFO['name'] == 'lucy' and USER_INFO['pwd'] == '123456' :
            # 设置cookie,创建
            # self.set_cookie('auth','1',expires = time.time()+10)   # 10秒之后过期
            self.set_cookie('auth','1',expires_days = 7 )  # 7天免登陆
        self.redirect('/index')

# 添加新栏目
class NewsHandler(tornado.web.RequestHandler):
    def post(self, *args, **kwargs):
        NEW_INPUT = {}
        NEW_INPUT['title'] = self.get_argument('title',None)
        NEW_INPUT['content'] = self.get_argument('content',None)
        NEWS_LIST.append(NEW_INPUT)
        self.redirect('/index') # 跳转

# 用户退出登录
class LogoutHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.set_cookie('auth','0')    # 重置cookie,删除
        self.redirect('/index')



# 路径解析
settings = {
    "template_path":"templates",
    "static_path":"statics",
    "static_url_prefix":"/sss/",
    "cookie_secret":"jfoijfoiewfierr",
}


# 路由至具体的事件句柄
application = tornado.web.Application([
    (r"/index",IndexHandler),
    (r"/login",LoginHandler),
    (r"/news",NewsHandler),
    (r"/logout",LogoutHandler),
],**settings)

# 开启服务器,监听
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
View Code

 二、基于浏览器设置cookie:界面缩放等用户自定义版面信息的设置等,

(一)基于JavaScript的cookie设置 

1、获取cookie:document.cookie

 这里获取的是含有全部cookie的字符串,每一个cookie之间用‘;’间隔,

JavaScript无法直接获取单个的cookie,后台可以进行单个cookie的获取是因为tornado做了相关处理,

需要获得单个cookie,需要拆分字符串:document.cookie.spilt(‘;’)

2、设置cookie:document.cookie = “key=value”

这里可以设置path、expires(秒)、domain、secure等参数,

3、在html中通过JavaScript设置:

<input type="button" onclick="setCookieBySeconds('k1','123',6)" />      <!--6秒后过期-->
    <input type="button" onclick="setCookieByDays('k2','456',7)" />         <!--7天后过期-->
    <script>
        <!--设置cookie,指定秒数过期-->
        function setCookieBySeconds(name,value,expires){
            var current_date = new Date();
            current_date.setSeconds(current_date.getSeconds()+expires);
            document.cookie = name + "=" + value + ";expires=" + current_date.toUTCString();
        }

        <!--设置cookie,指定天数过期-->
        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();
        }
    </script>
View Code

(二)基于jQuery Cookie的设置

 jQuery Cookie是一个插件,使用前需要:先导入jQuery、再导入jQuery Cookie,才能使用,

语法:$.cookie(‘key’,‘value’,{path:‘’,domain:‘’,expires=7})

    <script rel="stylesheet" src='{{static_url("js/jquery-1.12.4.min.js")}}'></script>
    <script rel="stylesheet" src='{{static_url("js/jquery.cookie.js")}}'></script>
    <script>
        <!--jquery.cookie默认按天数设置有效期-->
        $.cookie('k1','v1',{expires:7});                    //7天

        <!--按秒数设置有效期需要自定义-->
        var current_date = new Date();
        current_date.setSeconds(current_date.getSeconds() + 6 )
        $.cookie('k1','v1',{expires:current_date})          //6秒
    </script>
View Code

 其中:

expires:(Number|Date)有效期;设置一个整数时,单位是天;也可以设置一个日期对象作为Cookie的过期日期;
path:(String)创建该Cookie的页面路径;
domain:(String)创建该Cookie的页面域名;
secure:(Booblean)如果设为true,那么此Cookie的传输会要求一个安全协议,例如:HTTPS;