为Tornado框架加上基于Redis或Memcached的session 【第三方】

Tornado 没有session,只有cookie_secret,这在一些情况下是不利于开发的。所有我们可以给Tornado加上session的功能。

这篇文章讲解的是依靠第三方包来实现。以后的文章我们还可以自己写一套。

以下为步骤:

1,安装包 pycket 

$ pip install pycket

 

2,使用时引入包

from pycket.session import SessionMixin

 

3,通过Handler传入(还可以创建一个BaseHandler,将其封装到BaseHandler也可以。这里为了简单,就不封装了)

4,在配置文件中进行配置

'''
        Redis 配置
        '''
        # settings = {
        #     # cookie_secret必须设置
        #     'cookie_secret': "2379874hsdhf0234990sdhsaiuofyasop977djdj",
        #     'xsrf_cookies': True,
        #     'debug': False,
        #     # 1 配置pycket 注意别忘记开启redis服务
        #     'pycket': {
        #         'engine': 'redis',
        #         'storage': {
        #             'host': 'localhost',
        #             'port': 6379,
        #             'db_sessions': 10,
        #             'db_notifications': 11,
        #             'max_connections': 2 ** 31,
        #         },
        #         'cookies': {
        #             # 设置过期时间
        #             'expires_days': 2,
        #             #'expires':None, #秒
        #         },
        #     }
        # }
        '''
        Memcached 配置
        '''
        settings = {
            'cookie_secret': "2379874hsdhf0234990sdhsaiuofyasop977djdj",
            'pycket': {
                'engine': 'memcached',
                'storage': {
                    'servers': ('localhost:11211',)
                },
                'cookies': {
                    'expires_days': 120,
                },
            },
        }

5,使用

    def get(self):
        # 两种设置方式
        self.session.set('foo', ['bar', 'baz'])
        self.session['test'] = 'test!'

        # 两种获取方式
        print self.session['test']
        print self.session.get('foo')

 

完整代码:

 1 #--*--coding:utf-8--*--
 2 
 3 import tornado.web
 4 import tornado.httpserver
 5 import tornado.ioloop
 6 import tornado.options
 7 import os.path
 8 from pycket.session import SessionMixin
 9 from tornado.options import define, options
10 define("port", default=8001, help="run on the given port", type=int)
11 
12 
13 class Application(tornado.web.Application):
14     def __init__(self):
15         handlers = [
16             (r"/", MainHandler),
17         ]
18         '''
19         Redis 配置
20         '''
21         # settings = {
22         #     # cookie_secret必须设置
23         #     'cookie_secret': "2379874hsdhf0234990sdhsaiuofyasop977djdj",
24         #     'xsrf_cookies': True,
25         #     'debug': False,
26         #     # 1 配置pycket 注意别忘记开启redis服务
27         #     'pycket': {
28         #         'engine': 'redis',
29         #         'storage': {
30         #             'host': 'localhost',
31         #             'port': 6379,
32         #             'db_sessions': 10,
33         #             'db_notifications': 11,
34         #             'max_connections': 2 ** 31,
35         #         },
36         #         'cookies': {
37         #             # 设置过期时间
38         #             'expires_days': 2,
39         #             #'expires':None, #秒
40         #         },
41         #     }
42         # }
43         '''
44         Memcached 配置
45         '''
46         settings = {
47             'cookie_secret': "2379874hsdhf0234990sdhsaiuofyasop977djdj",
48             'pycket': {
49                 'engine': 'memcached',
50                 'storage': {
51                     'servers': ('localhost:11211',)
52                 },
53                 'cookies': {
54                     'expires_days': 120,
55                 },
56             },
57         }
58         tornado.web.Application.__init__(self, handlers, **settings)
59 
60 
61 class MainHandler(tornado.web.RequestHandler, SessionMixin):
62     def get(self):
63         # 两种设置方式
64         self.session.set('foo', ['bar', 'baz'])
65         self.session['test'] = 'test!'
66 
67         # 两种获取方式
68         print self.session['test']
69         print self.session.get('foo')
70 
71 if __name__ == "__main__":
72     tornado.options.parse_command_line()
73     http_server = tornado.httpserver.HTTPServer(Application())
74     http_server.listen(options.port)
75     tornado.ioloop.IOLoop.instance().start()
View Code

注意:若使用Redis,确保你的Redis已经启动。若使用 Memcached ,请确保Memcached 已经启动

 

posted @ 2017-07-27 12:25  Rex_Blog  阅读(1082)  评论(0编辑  收藏  举报