Session for Tornado(Redis) - 代码分享
Session for Tornado(Redis)
session id的生成借用了web.py。
使用了 redis 的 hash 储存。
只有在为session赋值的时候才会生成session_id,是为了必要的情况下的使用(例如oAuth2的state和验证码)
[代码] [Python]代码
#coding=utf8 import os, time from core.options import options from hashlib import sha1 class Session(object): _prefix = "_session:" _id = None _skip = ['_redis','_request','_id'] def __init__(self,request): self._redis = request.redis self._request = request #init session id id = request.get_secure_cookie('sessionid') if id and self._redis.exists(id): self._id = id def init_session(self): """初始化""" if not self._id: self._id = self.generate_session_id() self._request.set_secure_cookie('sessionid',self._id) #延期过期时间 self._redis.hset(self._id,'lastActive',time.time()) self._redis.expire(self._id,options.session_maxlifetime) def generate_session_id(self): """Generate a random id for session""" secret_key = self._request.settings['cookie_secret'] ip = self._request.request.remote_ip while True: rand = os.urandom(16) now = time.time() sessionid = sha1("%s%s%s%s" % (rand, now,ip, secret_key)) sessionid = self._prefix + sessionid.hexdigest() if not self._redis.exists(sessionid): break return sessionid def __getattr__(self, name): if self._id: return self._redis.hget(self._id,name) return object.__getattribute__(self, name) def __setattr__(self, name, value): if not name in self._skip: self.init_session() self._redis.hset(self._id,name,value) object.__setattr__(self, name, value) def __delattr__(self, name): if not name in self._skip: return self._redis.hdel(self._id,name) object.__delattr__(self, name)