[py]tornado诠释cookie

tornado返回一个index.html

start.py

#!/usr/bin/env python
# coding=utf-8



import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        # self.write("Hello, world")
        # self.render("index.html")

settings = {
    'template_path': 'templates',
    'static_path': 'static',
    'static_url_prefix': '/statics/',
}

application = tornado.web.Application([
    (r"/index", MainHandler),
],**settings)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<script>
    function setCookie(name, value, expires) {
        var temp = [];
        var current_date = new Date();
        current_date.setSeconds(current_date.getSeconds() + 5);
        document.cookie = name + "= " + value + ";expires=" + current_date.toUTCString();
    }
</script>
</body>
</html>

后端设置cookie方法:

tornado对cookie的基本操作

语法格式:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_cookie("mycookie"):
            self.set_cookie("mycookie", "myvalue")
            self.write("Your cookie was not set yet!")
        else:
            self.write("Your cookie was set!")

操作:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        print(self.cookies)             # 打印前端发来的所有cookie.
        self.set_cookie("k1", "1111")   # 设置一个cookie
        print(self.get_cookie("k1"))    # 获取某个cookie
        self.render("index.html")

tornado操作cookie的参数

  • tornado设置cookie格式:
self.set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs)
  • tornado设置cookie栗子:设置cookie超时时间为900s
self.set_cookie('key', 'value', expires=time.time()+900) 
  • 参数有这些:

通过浏览器js设置cookie:

直接通过console用命令的方式设置cookie

  • 设置cookie常用操作
document.cookie = "test1=Hello";
document.cookie = "test2=World";

document.cookie="age=12; expires=Thu, 26 Feb 2116 11:50:25 GMT; domain=sankuai.com; path=/";

查询时属性不会显示

  • 获取cookie test2的值
var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
alert(myCookie);
  • 同时设置多个cookie
document.cookie = "name=Jonh";
document.cookie = "age=12";
document.cookie = "class=111";

document.cookie = "name=Jonh; age=12; class=111"; 只能添加第一个

增删改查cookie参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie

使用函数法设置cookie(s为单位,时间要处理为toUTCString())

  • index.html里定义cookie,前端浏览器console调用函数
    function setCookie(name, value, expires) {
        var temp = [];
        var current_date = new Date();
        current_date.setSeconds(current_date.getSeconds() + 5);
        document.cookie = name + "= " + value + ";expires=" + current_date.toUTCString();
    }
  • 设置一个带时间的cookie

小结: 通过jq和操作cookie

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cookie</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script>
</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>

jq操作cookie

下载

$.cookie(’the_cookie’, ‘the_value’); //新建cookie

$.cookie(’the_cookie’, null); //删除一个cookie
$.cookie('the_cookie'); //读取Cookie$.cookie(’the_cookie’, ‘the_value’); //设置cookie的值

$.cookie(’the_cookie’, ‘the_value’, {expires: 7, path: ‘/’, domain: ‘jquery.com’, secure: true});//新建一个cookie 包括有效期 路径 域名等

使用签名的cookie

tornado签名cookie使用

start.py

#!/usr/bin/env python
# coding=utf-8



import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie("mycookie"):
            self.set_secure_cookie("mycookie", "myvalue")
            self.write("Your cookie was not set yet!")
        else:
            self.write("Your cookie was set!")

settings = {
    'template_path': 'templates',
    'static_path': 'static',
    'static_url_prefix': '/statics/',
}

application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings,cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")


if __name__ == "__main__":
    print('http://127.0.0.1:8888/')
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

使用带签名的cookie做的一个: 用户登陆案例

效果

完整代码:

start.py

import tornado.web
import tornado.ioloop


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_secure_cookie('username', 'maotai')
        self.set_secure_cookie('password', '123456')
        self.render('login.html')

    def post(self, *args, **kwargs):
        username = self.get_argument('username', None)
        password = self.get_argument('password', None)
        cooike_user = str(self.get_secure_cookie('username'), encoding='utf-8')
        cooike_pass = str(self.get_secure_cookie('password'), encoding='utf-8')
        if username == cooike_user and password == cooike_pass:
            self.write('Hello ' + cooike_user)
        else:
            self.write('用户名或密码错误')


settings = {
    'template_path': 'templates',
}

application = tornado.web.Application([
    (r'/', IndexHandler),
], **settings,
    cookie_secret="508CE6152CB93994628D3E99934B83CC")

if __name__ == '__main__':
    print('http://127.0.0.1:8888')
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form action="/" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit" value="登陆">
</form>

</body>
</html>

tornado的session与cookie

在Tornado中是不提供像Cookie这种直接设置Session的,需要我们自己写插件来进行对Session的增删改
Session的数据是保存在服务端的,如果要应用Session必须要依赖Cookie,因为Cookie的值就等于Session的Key

  • Session在内存中的存储方式如下:
key(随机字符串) = {
    {'k1','v1'},
    {'k2','v2'},
    {'k3','v3'},
    ....
}

key(随机字符串) = {
    {'k1','v1'},
    {'k2','v2'},
    {'k3','v3'},
    ....
}

key(随机字符串) = {
    {'k1','v1'},
    {'k2','v2'},
    {'k3','v3'},
    ....
}

.....
  • cookie和session关系图解

参考:http://www.cnblogs.com/xinsiwei18/p/5836381.html

一个设置与获取Session的小脚本:

代码逻辑:

完整code:

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

import tornado.web
import tornado.ioloop

container = {}


class Session:
    def __init__(self, Handler):
        self.Handler = Handler
        self.random_str = None

    # 生成随机字符串
    def __genarate_random_str(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 self.random_str == None:
            random_str = self.Handler.get_cookie('uc')
            if not self.random_str:
                random_str = self.__genarate_random_str()
                container[random_str] = {}

            else:
                if self.random_str in container.keys():
                    pass
                else:
                    random_str = self.__genarate_random_str()
                    container[random_str] = {}
            self.random_str = random_str

        container[self.random_str][key] = value
        # 浏览器写入Cookie
        self.Handler.set_cookie('uc', self.random_str)

    # 获取cookie
    def __getitem__(self, key):
        random_str = self.Handler.get_cookie('uc')
        if not random_str:
            return None
        user_info_dict = container.get(random_str, None)
        if not user_info_dict:
            return None
        value = user_info_dict.get(key, None)
        return value


class BaseHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.session = Session(self)


class SetHandler(BaseHandler):
    def get(self, *args, **kwargs):
        self.session['Hello'] = 'World'
        self.write('OK')


class GetHandler(BaseHandler):
    def get(self, *args, **kwargs):
        val = self.session['Hello']
        self.write(val)


application = tornado.web.Application([
    (r'/set', SetHandler),
    (r'/get', GetHandler),
])

if __name__ == '__main__':
    print('http://127.0.0.1:8000')
    application.listen(8000)
    tornado.ioloop.IOLoop.instance().start()

2017年8月29日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值