vfclcm upgrade from python2 to python3
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / redisco / containers.py
1 """
2 This module contains the container classes to create objects
3 that persist directly in a Redis server.
4 """
5
6 import collections
7 from functools import partial
8
9
10 class Container(object):
11     """Create a container object saved in Redis.
12
13     Arguments:
14         key -- the Redis key this container is stored at
15         db  -- the Redis client object. Default: None
16
17     When ``db`` is not set, the gets the default connection from
18     ``redisco.connection`` module.
19     """
20
21     def __init__(self, key, db=None, pipeline=None):
22         self._db = db
23         self.key = key
24         self.pipeline = pipeline
25
26     def clear(self):
27         """Remove container from Redis database."""
28         del self.db[self.key]
29
30     def __getattribute__(self, att):
31         if att in object.__getattribute__(self, 'DELEGATEABLE_METHODS'):
32             return partial(getattr(object.__getattribute__(self, 'db'), att), self.key)
33         else:
34             return object.__getattribute__(self, att)
35
36     @property
37     def db(self):
38         if self.pipeline:
39             return self.pipeline
40         if self._db:
41             return self._db
42         if hasattr(self, 'db_cache') and self.db_cache:
43             return self.db_cache
44         else:
45             from redisco import connection
46             self.db_cache = connection
47             return self.db_cache
48
49     DELEGATEABLE_METHODS = ()
50
51
52 class Hash(Container, collections.MutableMapping):
53
54     def __getitem__(self, att):
55         return self.hget(att)
56
57     def __setitem__(self, att, val):
58         self.hset(att, val)
59
60     def __delitem__(self, att):
61         self.hdel(att)
62
63     def __len__(self):
64         return self.hlen()
65
66     def __iter__(self):
67         return self.hgetall().__iter__()
68
69     def __contains__(self, att):
70         return self.hexists(att)
71
72     def __repr__(self):
73         return "<%s '%s' %s>" % (self.__class__.__name__, self.key, self.hgetall())
74
75     def keys(self):
76         return self.hkeys()
77
78     def values(self):
79         return self.hvals()
80
81     def _get_dict(self):
82         return self.hgetall()
83
84     def _set_dict(self, new_dict):
85         self.clear()
86         self.update(new_dict)
87
88     dict = property(_get_dict, _set_dict)
89
90     DELEGATEABLE_METHODS = ('hlen', 'hset', 'hdel', 'hkeys', 'hgetall', 'hvals',
91                             'hget', 'hexists', 'hincrby', 'hmget', 'hmset')