Beispiel #1
0
    def put(self):
        def fixval(d):
            if type(d) == datetime.datetime:
                # avoids mysqldb reliance on strftime that lacks support for dates before 1900
                return "%02d-%02d-%02d %02d:%02d:%02d" % (d.year,d.month,d.day,d.hour,d.minute,d.second)
            else:
                return d                
    
        if not self.valid():
            return 0

        keys        = [i for i in self.__dict__.keys() if i<>'id']
        values      = [self.__dict__[i] for i in keys]
        datatypes   = [repr(type(i)).strip("<type >").strip("'") for i in values]
        values      = [fixval(i) for i in values] # same fix as above
        valid_types = ['str','unicode','long','int','float','datetime.date','datetime.datetime','bool','NoneType']

        for atype in datatypes:
            if atype not in valid_types:
                raise TypeException,'unsupported type <type %s>' % atype

        if hasattr(self,'id') and self.exists(self.id):
            db('delete from storage_values where row_id=%s',self.id)
        else:
            db('insert into storage_entities (kind) values (%s)',self.kind())
            self.id = db.lastrowid

        keys = [key.lower() for key in keys] # store attribute names as lower case
        param_list = zip([self.kind()]*len(keys),[self.id]*len(keys),keys,datatypes,values)

        cmd = 'insert into storage_values (kind,row_id,attribute,datatype,value) values (%s,%s,%s,%s,%s)'
        db.cursor().executemany(cmd,param_list)

        return self.id
Beispiel #2
0
 def trysid(sid):
     cmd = "INSERT INTO %s VALUES (%s,%s,'A','')" % (self.tablename,'%s','%s')
     try:
         db(cmd,newsid,expiry)
         return 1
     except:
         raise
Beispiel #3
0
 def destroy_session(self, sid=None):
     sid = sid or self.sid
     self.__dict__.clear()
     
     if system.config.get('sessions', 'destroy', True):
         cmd = 'delete from %s where sesskey=%s' % (self.tablename, '%s')
         db(cmd, sid)
     else:
         cmd = 'update %s set expiry=%s, status="D" where sesskey=%s' % (self.tablename, '%s', '%s')
         db(cmd, time.time(), sid)
Beispiel #4
0
        def test(self):

            #Create session object
            session = Session()

            #Create new session
            id = session.new_session()
            self.assert_(id!='Session error')
            session.MyName = 'Test'
            session.Message = 'This is a test session'
            session.Number = 123

            #Save session
            session.save_session(id)
            self.assertEqual(len(db('select * from '+session.tablename+' where sesskey="'+id+'"').__dict__['data']),1)

            # Create new session object
            session2 = Session()

            # Load above session
            session2.load_session(id)
            self.assertEqual(session2.Number,123)
            self.assertEqual(session2.MyName,'Test')
            self.assertEqual(session2.Message,'This is a test session')
            session2.destroy_session(id)
            if not debug:
               self.assertEqual(len(session.exec_SQL('select * from '+session.tablename+' where sesskey="'+id+'"').__dict__['data']),0)
Beispiel #5
0
def create_storage():
    db("""
    create table if not exists storage_entities (
        id int not null auto_increment,
        kind      varchar(100),
        PRIMARY KEY (id)
        )
    """)
    db("""
    create table if not exists storage_values (
        id int not null auto_increment,
        kind      varchar(100),
        row_id    int not null,
        attribute varchar(100),
        datatype  varchar(30),
        value     text,
        PRIMARY KEY (id)
        )
    """)
Beispiel #6
0
 def save_session(self,response, sid=None, timeout=sessionLife):
     sid = sid or self.sid
     expiry = time.time() + timeout * 60
     values = {}
     for key in self.__dict__.keys():
         if key[0] != '_':
             values[key] = self.__dict__[key]
     value = pickle.dumps(values)
     cmd = 'UPDATE %s SET expiry=%s, value=%s WHERE sesskey=%s' % (self.tablename,'%s','%s','%s')
     curs = db(cmd,expiry,value,sid)
     set_session_cookie(response, session.sid, request.host, sessionLife, system.secure_cookies)
Beispiel #7
0
 def load_existing(sid):
     cmd = "SELECT * FROM %s WHERE sesskey=%s AND expiry>%s and status='A'" %(self.tablename,'%s','%s')
     curs = db(cmd, sid, time.time())
     if len(curs):
         try:
             values = (curs[0].VALUE and pickle.loads(curs[0].VALUE) or {})
         except:
             values = {}                
         for key in values:
             self.__dict__[key] = values[key]
         return True
Beispiel #8
0
    def exists(cls,keys=None):
        if not isinstance(keys, (list, tuple)):
            keys = (keys,)
        slots = (','.join(['%s']*len(keys)))
        cmd = 'select * from storage_entities where id in (%s)' % slots
        rs = db(cmd,*keys)

        found_keys = [rec.ID for rec in rs]
        if len(keys)>1:
            result = [(key in found_keys) for key in keys]
        else:
            result = keys[0] in found_keys
        return result
Beispiel #9
0
 def find(cls,limit=1000,**kv):
     all_keys = []
     for field_name in kv.keys():
         value = kv[field_name]
         if not isinstance(value, (list, tuple)):
             wc = 'value=%s'
             v = (value,)
         else:
             wc = 'value in ('+','.join(['%s']*len(value))+')'
             v = value
         cmd = 'select distinct row_id from storage_values where kind=%s and attribute=%s and '+wc+' limit %s' % limit
         rs = db(cmd,cls.kind(),field_name.lower(),*v)
         all_keys.append([rec.ROW_ID for rec in rs])
     answer = set(all_keys[0])
     for keys in all_keys[1:]:
         answer = set(keys) & answer
     if answer:
         return cls.get(list(answer))
     else:
         return []
Beispiel #10
0
 def len(cls):
     cmd = 'select count(*) n from storage_entities where kind=%s'
     return db(cmd,cls.kind())[0].N
Beispiel #11
0
 def zap(cls):
     cmd = 'delete from storage_values where kind=%s'
     db(cmd,cls.kind())
     cmd = 'delete from storage_entities where kind=%s'
     db(cmd,cls.kind())
Beispiel #12
0
 def all(cls,limit=1000):
     cmd = 'select distinct row_id from storage_values where kind="%s" limit %s' % (cls.kind(),limit)
     rs = db(cmd)
     keys = [rec.ROW_ID for rec in rs]
     return cls.get(keys) or EntityList()
Beispiel #13
0
    def get(cls,keys):
        if keys == None: return None
        if not isinstance(keys, (list, tuple)):
            keys = (keys,)
            as_list = 0
        else:
            as_list = 1
        keys = [long(key) for key in keys]

        if not keys:
            if as_list:
                return []
            else:
                return None

        cmd = 'select * from storage_values where kind=%s and row_id in (%s)' % ('%s',','.join(['%s']*len(keys)))
        entities = {}
        rs = db(cmd,cls.kind(),*keys)

        for rec in rs:
            row_id = rec.ROW_ID
            attribute = rec.ATTRIBUTE.lower()
            if rec.DATATYPE == "str":
                value = rec.VALUE
            elif rec.DATATYPE == 'unicode':
                value = rec.VALUE                
            elif rec.DATATYPE == "long":
                value = long(rec.VALUE)
            elif rec.DATATYPE == "int":
                value = int(rec.VALUE)
            elif rec.DATATYPE == 'float':
                value = float(rec.VALUE)
            elif rec.DATATYPE == "datetime.date":
                y = int(rec.VALUE[:4])
                m = int(rec.VALUE[5:7])
                d = int(rec.VALUE[8:10])
                import datetime
                value = datetime.date(y,m,d)
            elif rec.DATATYPE == "datetime.datetime":
                y = int(rec.VALUE[:4])
                m = int(rec.VALUE[5:7])
                d = int(rec.VALUE[8:10])
                hr = int(rec.VALUE[11:13])
                mn = int(rec.VALUE[14:16])
                sc = int(rec.VALUE[17:19])
                import datetime
                value = datetime.datetime(y,m,d,hr,mn,sc)
            elif rec.DATATYPE == 'bool':
                value = (rec.VALUE == '1' or rec.VALUE == 'True')
            elif rec.DATATYPE == 'NoneType':
                value = None
            elif rec.DATATYPE == 'instance':
#                print 'dzstore:','(id=%s name="%s" type=%s value=%s)'%(rec.id,attribute,repr(rec.DATATYPE),repr(rec.VALUE))
                value = long(rec.id)
            else:
                print 'dzstore:',rec.DATATYPE,'not supported (name="%s" type=%s value=%s id=%s)'%(attribute,repr(rec.DATATYPE),repr(rec.VALUE),rec.id)
                value = rec.VALUE
            entities.setdefault(row_id,cls(_id=row_id)).__dict__[attribute] = value

        if len(keys)>1:
            result = EntityList()
            for id in keys: result.append(entities.get(id))
#            result = [entities.get(id) for id in keys]
        else:
            if as_list:
                result = EntityList()
                result.append(entities.get(keys[0]))
            else:
                result = entities.get(keys[0])


        return result
Beispiel #14
0
 def delete(self):
     cmd = 'delete from storage_values where row_id=%s'
     db(cmd,self.id)
Beispiel #15
0
 def attributes(cls):
     cmd = 'select distinct attribute from storage_values where kind=%s order by id desc'
     rs = db(cmd,cls.kind())
     values = [rec.ATTRIBUTE for rec in rs]
     return values
Beispiel #16
0
def delete_storage():
    db('drop table if exists storage_values')
    db('drop table if exists storage_entities')
Beispiel #17
0
 def gc(self):
     if system.config.get('session', 'destroy', True):
         cmd = 'DELETE FROM %s WHERE (expiry < %s) or (status="D")' % (self.tablename,'%s')
         db(cmd,time.time())