def cookie_decode(data, key): ''' Verify and decode an encoded string. Return an object or None.''' data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(key, msg).digest())): return pickle.loads(base64.b64decode(msg)) return None
def get_object(self, id=None,use_cache=True): session=self.session() raw_id = "o-%s" % tob(id) if use_cache: try: if session.check_obj(raw_id): data = session.get_obj(raw_id) if "_auto_id" in data: return loads(data) except: log(ERROR,"CACHE read error") sql = "SELECT `auto_id`,`id`,`object`,`updated` FROM `"+self.table+"` WHERE `id`=%s" rows = session.connection.query(sql, tou(id)) if rows: data = rows[0].object objstr = decompress(data) obj = loads(objstr) obj.update(dict(id=id)) obj["_updated"] = rows[0].updated obj["_auto_id"] =rows[0].auto_id if use_cache: try: session.set_obj(raw_id,dumps(obj)) except: log(ERROR,"CACHE write error") return obj
def set_object(self, id=None, object=None): session=self.session() r_data=dumps(object) datas = compress(r_data) if not id: entity_id = myid() else: entity_id = id timestamp=datetime.datetime.now() sql = "INSERT INTO `" + self.table + "` (`id`,`object`,`updated`) VALUES (%s,%s,%s)" ret=session.connection.execute(sql, entity_id, datas,timestamp) raw_id = "o-%s" % tob(entity_id) return entity_id,ret
def cookie_encode(data, key): ''' Encode and sign a pickle-able object. Return a (byte) string ''' msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(key, msg).digest()) return tob('!') + sig + tob('?') + msg
def cookie_is_encoded(data): ''' Return True if the argument looks like a encoded cookie.''' return bool(data.startswith(tob('!')) and tob('?') in data)