tornado-cookies+pycket 验证

本文介绍如何在Tornado框架中使用Pycket库进行会话管理,包括安装依赖库、配置设置、构建BaseHandler类、实现登录验证及登出功能。通过设置cookie和redis存储,实现用户登录状态的持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.pip install pycket

 pip install redis

2.config

复制代码

        settings = dict(
            debug=True,
            template_path='templates',
            static_path='static',
       cookie_secret='secret',
            pycket={
                'engine': 'redis',
                'storage': {
                    'host': 'localhost',
                    'port': 6379,
                    'db_sessions': 2,
                    # 'password': '',
                    'db_notifications': 11,
                    'max_connections': 2 ** 31,
                },
                'cookies': {
                    'expires_days': 30,
                    'max_age': 5000
                }
            },
        )

复制代码

 3.构建BaseHandler

from pycket.session import SessionMixin

class BaseHandler(tornado.web.RequestHandler, SessionMixin):
    def get_current_user(self):
        return self.session.get('cookie_name')

 

4.需要设置一个条件去验证,比如要求用户登录。就在用户登录的handler中设置一个cookie信息

复制代码

class LoginHandler(BaseHandler):
  def get(self):
     username = self.get_argument('username')
    passwd = self.get_argument('password')
    if username in db and passwd == db.passwd:
      self.sesion.set('cookie_name', value)
      self.write('success login')

复制代码

5.其他handler需要继承basehandler才能够使用装饰起@tornado.web.authenticated去验证用户是否登录

class NoLoginNoShow(BaseHandler):
  @tornado.web.authenticated
  def get(self):
    self.write('this message is secrect'

6.登出,可以通过self.session.delete('cookie_name')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值