settings.py 18.6 KB
Newer Older
1
from .conductor.client import Client
Matias Guijarro's avatar
Matias Guijarro committed
2 3 4 5 6
import weakref
import pickle
import redis

def get_cache():
7
    return Client.get_cache(db=0)
Matias Guijarro's avatar
Matias Guijarro committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

def boolify(s,**keys):
    if s == 'True' or s == 'true':
            return True
    if s == 'False' or s == 'false':
            return False
    raise ValueError('Not Boolean Value!')

def auto_conversion(var):
    '''guesses the str representation of the variables type'''
    if var is None:
        return None
    for caster in (boolify,int, float):
        try:
            return caster(var)
        except ValueError:
            pass
    return var

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
27
def pickle_loads(var) :
Matias Guijarro's avatar
Matias Guijarro committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    if var is None:
        return None
    return pickle.loads(var)

def ttl_func(cnx,name,value = -1):
    if value is None:
        return cnx.persist(name)
    elif value is -1:
        return cnx.ttl(name)
    else:
        return cnx.expire(name,value)

def read_decorator(func) :
    def _read(self,*args,**keys) :
        value = func(self,*args,**keys)
        if self._read_type_conversion:
            if isinstance(value,list) :
                value = [self._read_type_conversion(x) for x in value]
            elif isinstance(value,dict) :
                for k,v in value.iteritems():
                    value[k] = self._read_type_conversion(v)
49 50 51 52
                if hasattr(self,'default_values') and isinstance(self.default_values,dict):
                    tmp = dict(self._default_values)
                    tmp.update(value)
                    value = tmp
Matias Guijarro's avatar
Matias Guijarro committed
53 54
            else:
                value = self._read_type_conversion(value)
55 56 57 58 59 60
        if value is None:
            if hasattr(self,'_default_value'):
                value = self._default_value
            elif(hasattr(self,'_default_values') and 
                 hasattr(self._default_values,'get')):
                value = self._default_values.get(args[0])
Matias Guijarro's avatar
Matias Guijarro committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        return value
    return _read

def write_decorator_dict(func) :
    def _write(self,values,**keys) :
        if self._write_type_conversion:
            if not isinstance(values,dict) and values is not None:
                raise TypeError('can only be dict')

            if values is not None:
                for k,v in values.iteritems():
                    values[k] = self._write_type_conversion(v)
        return func(self,values,**keys)
    return _write

def write_decorator_multiple(func) :
    def _write(self,values,**keys):
        if self._write_type_conversion:
            if not isinstance(values,(list,tuple)) and values is not None:
                raise TypeError('can only be tuple or list')
            if values is not None:
                values = [self._write_type_conversion(x) for x in values]
        return func(self,values,**keys)
    return _write

def write_decorator(func) :
    def _write(self,value,**keys):
        if self._write_type_conversion and value is not None:
            value = self._write_type_conversion(value)
        return func(self,value,**keys)
    return _write

class SimpleSetting(object) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
94 95
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
96 97
                 write_type_conversion = None,
                 default_value = None) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
98 99 100 101 102 103
        if connection is None:
            connection = get_cache()
        self._cnx = weakref.ref(connection)
        self._name = name
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
104
        self._default_value = default_value
Matias Guijarro's avatar
Matias Guijarro committed
105

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    @read_decorator
    def get(self) :
        cnx = self._cnx()
        value = cnx.get(self._name)
        return value

    @write_decorator
    def set(self,value) :
        cnx = self._cnx()
        cnx.set(self._name,value)

    def ttl(self,value = -1):
        return ttl_func(self._cnx(),self._name,value)

    def __add__(self,other) :
        value = self.get()
122
        if isinstance(other,SimpleSetting):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
123 124 125 126 127 128 129 130 131
            other = other.get()
        return value + other

    def __iadd__(self,other):
        cnx = self._cnx()
        if cnx is not None:
            if isinstance(other,int) :
                if other == 1:
                    cnx.incr(self._name)
Matias Guijarro's avatar
Matias Guijarro committed
132
                else:
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
133 134 135 136 137 138
                    cnx.incrby(self._name,other)
            elif isinstance(other,float) :
                cnx.incrbyfloat(self._name,other)
            else:
                cnx.append(self._name,other)
            return self
Matias Guijarro's avatar
Matias Guijarro committed
139

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
140 141 142 143
    def __isub__(self,other) :
        if isinstance(other,basestring):
            raise TypeError("unsupported operand type(s) for -=: %s" % type(other).__name__)
        return self.__iadd__(-other)
Matias Guijarro's avatar
Matias Guijarro committed
144

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    def __getitem__(self,ran) :
        cnx = self._cnx()
        if cnx is not None:
            step = None
            if isinstance(ran,slice):
                i,j = ran.start,ran.stop
                step = ran.step
            elif isinstance(ran,int):
                i = j = ran
            else:
                raise TypeError('indices must be integers')

            value = cnx.getrange(self._name,i,j)
            if step is not None:
                value = value[0:-1:step]
            return value


    def __repr__(self):
        cnx = self._cnx()
        value = cnx.get(self._name)
166
        return '<SimpleSetting name=%s value=%s>' % (self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
167

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
168
class SimpleSettingProp(object) :
Matias Guijarro's avatar
Matias Guijarro committed
169 170 171
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None,
172
                 default_value = None,
Matias Guijarro's avatar
Matias Guijarro committed
173 174 175 176 177
                 use_object_name = True) :
        self._name = name
        self._cnx = connection or get_cache()
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
178
        self._default_value = default_value
Matias Guijarro's avatar
Matias Guijarro committed
179 180 181 182 183 184 185
        self._use_object_name = use_object_name

    def __get__(self,obj,type = None) :
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name
186 187 188 189
        return SimpleSetting(name,self._cnx,
                             self._read_type_conversion,
                             self._write_type_conversion,
                             self._default_value)
Matias Guijarro's avatar
Matias Guijarro committed
190 191

    def __set__(self,obj,value) :
192
        if isinstance(value,SimpleSetting): return
Matias Guijarro's avatar
Matias Guijarro committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206

        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

        if value is None:
            self._cnx.delete(name)
        else:
            if self._write_type_conversion:
                value = self._write_type_conversion(value)
            self._cnx.set(name,value)

class QueueSetting(object):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
207 208 209 210 211 212 213 214
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None) :
        if connection is None: connection = get_cache()
        self._cnx = weakref.ref(connection)
        self._name = name
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
Matias Guijarro's avatar
Matias Guijarro committed
215

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
216 217 218 219 220 221 222 223
    @read_decorator
    def get(self,first=0,last=-1) :
        cnx = self._cnx()
        if first == last:
            l = cnx.lindex(self._name,first)
        else:
            l = cnx.lrange(self._name,first,last)
        return l
Matias Guijarro's avatar
Matias Guijarro committed
224

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
225 226 227 228
    @write_decorator
    def append(self,value) :
        cnx = self._cnx()
        cnx.rpush(self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
229

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
230 231 232 233
    @write_decorator
    def prepend(self,value) :
        cnx = self._cnx()
        cnx.lpush(self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
234

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
235 236 237 238
    @write_decorator_multiple
    def extend(self,values) :
        cnx = self._cnx()
        cnx.rpush(self._name,*values)
Matias Guijarro's avatar
Matias Guijarro committed
239

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
240 241 242 243
    @write_decorator
    def remove(self,value) :
        cnx = self._cnx()
        cnx.lrem(self._name,1,value)
Matias Guijarro's avatar
Matias Guijarro committed
244

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
245 246 247 248
    @write_decorator_multiple
    def set(self,values) :
        if not isinstance(values,(list,tuple)) and values is not None:
            raise TypeError('can only be tuple or list')
Matias Guijarro's avatar
Matias Guijarro committed
249

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
250 251 252 253
        cnx = self._cnx()
        cnx.delete(self._name)
        if values is not None:
            cnx.rpush(self._name,*values)
Matias Guijarro's avatar
Matias Guijarro committed
254

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
255 256 257 258
    @write_decorator
    def set_item(self,value,pos = 0) :
        cnx = self._cnx()
        cnx.lset(self._name,pos,value)
Matias Guijarro's avatar
Matias Guijarro committed
259

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    @read_decorator
    def pop_front(self) :
        cnx = self._cnx()
        value = cnx.lpop(self._name)
        if self._read_type_conversion:
            value = self._read_type_conversion(value)
        return value

    @read_decorator
    def pop_back(self) :
        cnx = self._cnx()
        value = cnx.rpop(self._name)
        if self._read_type_conversion:
            value = self._read_type_conversion(value)
        return value

    def ttl(self,value = -1):
        return ttl_func(self._cnx(),self._name,value)

    def __len__(self) :
        cnx = self._cnx()
        return cnx.llen(self._name)

    def __repr__(self) :
        cnx = self._cnx()
        value = cnx.lrange(self._name,0,-1)
286
        return '<QueueSetting name=%s value=%s>' % (self._name,value)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
287 288 289 290 291 292 293

    def __iadd__(self,other):
        self.extend(other)
        return self

    def __getitem__(self,ran) :
        if isinstance(ran,slice):
294 295
            i = ran.start is not None and ran.start or 0
            j = ran.stop is not None and ran.stop or -1
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
296 297 298 299
        elif isinstance(ran,int):
            i = j = ran
        else:
            raise TypeError('indices must be integers')
300 301 302 303 304
        value = self.get(first = i,last = j)
        if value is None:
            raise StopIteration
        else:
            return value
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
305

306 307 308 309 310 311 312 313 314
    def __iter__(self) :
        cnx = self._cnx()
        lsize = cnx.llen(self._name)
        for first in xrange(0,lsize,1024) :
            last = first + 1024
            if last >= lsize: last = -1
            for value in self.get(first,last):
                yield value
        
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
315 316 317 318 319 320 321 322 323 324 325
    def __setitem__(self,ran,value):
        if isinstance(ran,slice) :
            for i,v in zip(range(ran.start,ran.stop),value) :
                self.set_item(v,pos=i)
        elif isinstance(ran,int):
            self.set_item(value,pos=ran)
        else:
            raise TypeError('indices must be integers')
        return self

class QueueSettingProp(object):
Matias Guijarro's avatar
Matias Guijarro committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None,
                 use_object_name = True) :
        self._name = name
        self._cnx = connection or get_cache()
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
        self._use_object_name = use_object_name

    def __get__(self,obj,type = None) :
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
342 343 344
        return QueueSetting(name,self._cnx,
                            self._read_type_conversion,
                            self._write_type_conversion)
Matias Guijarro's avatar
Matias Guijarro committed
345 346

    def __set__(self,obj,values) :
347
        if isinstance(values,QueueSetting): return
Matias Guijarro's avatar
Matias Guijarro committed
348 349 350 351 352 353

        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
354 355 356
        proxy = QueueSetting(name,self._cnx,
                             self._read_type_conversion,
                             self._write_type_conversion)
Matias Guijarro's avatar
Matias Guijarro committed
357 358 359 360 361
        proxy.set(values)

class HashSetting(object):
    def __init__(self,name,connection=None,
                 read_type_conversion=auto_conversion,
362 363
                 write_type_conversion=None,
                 default_values = {}):
Matias Guijarro's avatar
Matias Guijarro committed
364 365 366 367 368 369
        if connection is None:
            connection = get_cache()
        self._cnx = weakref.ref(connection)
        self._name = name
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
370
        self._default_values = default_values
Matias Guijarro's avatar
Matias Guijarro committed
371 372 373 374 375

    def __repr__(self) :
        cnx = self._cnx()
        value = cnx.hgetall(self._name)
        return '<HashSetting name=%s value=%s>' % (self._name,value)
376 377 378 379
    
    def __delitem__(self,key) :
        cnx = self._cnx()
        cnx.hdel(self._name,key)
Matias Guijarro's avatar
Matias Guijarro committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

    def __len__(self) :
        cnx = self._cnx()
        return cnx.hlen(self._name)

    def ttl(self,value = -1):
        return ttl_func(self._cnx(),self._name,value)

    @read_decorator
    def get(self,key) :
        cnx = self._cnx()
        return cnx.hget(self._name,key)

    @read_decorator
    def pop(self,key) :
        cnx = self._cnx()
        value = self.hget(self._name,key)
        self.hdel(self._name,key)
        return value
    
    def remove(self,key) :
        cnx = self._cnx()
        cnx.hdel(self._name,key)

    @read_decorator
    def get_all(self):
        cnx = self._cnx()
        return cnx.hgetall(self._name)
    
    def keys(self) :
410
        return list(self.iterkeys())
Matias Guijarro's avatar
Matias Guijarro committed
411 412

    def values(self) :
413
        return list(self.itervalues())
Matias Guijarro's avatar
Matias Guijarro committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

    def clear(self) :
        cnx = self._cnx()
        cnx.delete(self._name)

    def copy(self) :
        return self.get()

    @write_decorator_dict
    def set(self,values) :
        cnx = self._cnx()
        cnx.delete(self._name)
        if values is not None:
            cnx.hmset(self._name,values)

    @write_decorator_dict
    def update(self,values) :
        cnx = self._cnx()
        cnx.hmset(self._name,values)

    def items(self) :
        values = self.get_all()
        return [(k,v) for k,v in values.iteritems()]

    @read_decorator
    def fromkeys(self,keys) :
        cnx = self._cnx()
        return cnx.hmget(self._name,keys)
    
    def has_key(self,key) :
        cnx = self._cnx()
445
        return cnx.hexists(self._name,key) or self._default_values.has_key(key)
Matias Guijarro's avatar
Matias Guijarro committed
446 447
    
    def iterkeys(self):
448 449 450
        for k,v in self.iteritems():
            yield k

Matias Guijarro's avatar
Matias Guijarro committed
451
    def itervalues(self):
452 453
        for k,v in self.iteritems():
            yield v
Matias Guijarro's avatar
Matias Guijarro committed
454 455 456 457

    def iteritems(self) :
        cnx = self._cnx()
        next_id = 0
458
        seen_keys = set()
Matias Guijarro's avatar
Matias Guijarro committed
459 460 461 462 463
        while True:
            next_id,pd = cnx.hscan(self._name,next_id)
            for k,v in pd.iteritems():
                if self._read_type_conversion:
                    v = self._read_type_conversion(v)
464
                seen_keys.add(k)
Matias Guijarro's avatar
Matias Guijarro committed
465
                yield k,v
466
            if not next_id or next_id is '0':
Matias Guijarro's avatar
Matias Guijarro committed
467 468
                break

469 470 471 472
        for k,v in self._default_values.iteritems():
            if k in seen_keys: continue
            yield k,v

Matias Guijarro's avatar
Matias Guijarro committed
473 474 475 476 477 478 479 480
    def __getitem__(self,key):
        value = self.get(key)
        if value is None:
            raise KeyError(key)
        return value

    def __setitem__(self,key,value) :
        cnx = self._cnx()
481 482 483
        if value is None:
            cnx.hdel(self._name,key)
            return
Matias Guijarro's avatar
Matias Guijarro committed
484 485 486 487 488 489 490 491
        if self._write_type_conversion:
            value = self._write_type_conversion(value)
        cnx.hset(self._name,key,value)

class HashSettingProp(object):        
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None,
492
                 default_values = {},
Matias Guijarro's avatar
Matias Guijarro committed
493 494 495 496 497
                 use_object_name = True) :
        self._name = name
        self._cnx = connection or get_cache()
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
498
        self._default_values = default_values
Matias Guijarro's avatar
Matias Guijarro committed
499 500 501 502 503 504 505 506 507 508
        self._use_object_name = use_object_name

    def __get__(self,obj,type = None):
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name
    
        return HashSetting(name,self._cnx,
                           self._read_type_conversion,
509 510
                           self._write_type_conversion,
                           self._default_values)
Matias Guijarro's avatar
Matias Guijarro committed
511 512 513 514 515 516 517

    def __set__(self,obj,values) :
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

518
        if isinstance(values,HashSetting): return
Matias Guijarro's avatar
Matias Guijarro committed
519

520 521 522 523
        proxy = HashSetting(name,self._cnx,
                            self._read_type_conversion,
                            self._write_type_conversion,
                            self._default_values)
Matias Guijarro's avatar
Matias Guijarro committed
524 525 526 527 528
        proxy.set(values)
    
    def get_proxy(self) :
        return HashSetting(self._name,self._cnx,
                           self._read_type_conversion,
529 530
                           self._write_type_conversion,
                           self._default_values)
Matias Guijarro's avatar
Matias Guijarro committed
531 532
#helper

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
533 534 535 536 537 538
def _change_to_obj_marchaling(keys) :
    read_type_conversion = keys.pop('read_type_conversion',pickle_loads)
    write_type_conversion = keys.pop('write_type_conversion',pickle.dumps)
    keys.update({'read_type_conversion':read_type_conversion,
                 'write_type_conversion':write_type_conversion})

Matias Guijarro's avatar
Matias Guijarro committed
539
class HashObjSetting(HashSetting) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
540 541 542 543 544 545 546 547 548
    def __init__(self,name,**keys) :
        _change_to_obj_marchaling(keys)
        HashSetting.__init__(self,name,**keys)

class HashObjSettingProp(HashSettingProp) :
    def __init__(self,name,**keys):
        _change_to_obj_marchaling(keys)
        HashSettingProp.__init__(self,name,**keys)

Matias Guijarro's avatar
Matias Guijarro committed
549
class QueueObjSetting(QueueSetting) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
550 551 552 553 554 555 556 557 558
    def __init__(self,name,**keys) :
        _change_to_obj_marchaling(keys)
        QueueSetting.__init__(self,name,**keys)

class QueueObjSettingProp(QueueSettingProp):
    def __init__(self,name,**keys) :
        _change_to_obj_marchaling(keys)
        QueueSettingProp.__init__(self,name,**keys)

Matias Guijarro's avatar
Matias Guijarro committed
559
class SimpleObjSetting(SimpleSetting) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
560 561 562 563 564 565 566 567
    def __init__(self,name,**keys) :
        _change_to_obj_marchaling(keys)
        SimpleSetting.__init__(self,name,**keys)

class SimpleObjSettingProp(SimpleSettingProp):
    def __init__(self,name,**keys) :
        _change_to_obj_marchaling(keys)
        SimpleSettingProp.__init__(self,name,**keys)
Matias Guijarro's avatar
Matias Guijarro committed
568 569 570

class Struct(object):
    def __init__(self,name,**keys) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
571
        self._proxy = HashSetting(name,**keys)
Matias Guijarro's avatar
Matias Guijarro committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

    def __dir__(self) :
        return self._proxy.keys()

    def __repr__(self) :
        return "<Struct with attributes: %s>" % self._proxy.keys()

    def __getattribute__(self, name):
        if name.startswith('_'):
            return object.__getattribute__(self,name)
        else:
            return self._proxy.get(name)
            
    def __setattr__(self,name,value) :
        if name.startswith('_'):
            return object.__setattr__(self,name,value)
        else:
            self._proxy[name] = value
 
    def __delattr__(self,name) :
        if name.startswith('_'):
            return object.__delattr__(self,name)
        else:
            self._proxy.remove(name)

if __name__ == "__main__" :
    class A(object) :
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
599 600 601 602 603 604
        x = SimpleSettingProp('counter')
        y = SimpleObjSettingProp('obj')
        q = QueueSettingProp('seb')
        ol = QueueObjSettingProp('seb-list')
        h = HashSettingProp('seb-hash')
        oh = HashObjSettingProp('seb-hash-object')
Matias Guijarro's avatar
Matias Guijarro committed
605 606 607 608 609
        def __init__(self,name):
            self.name = name

    a = A('m0')
    p = Struct('optics:zap:params')