1 # Copyright (c) 2010 Tim Medina
3 # Permission is hereby granted, free of charge, to any person
4 # obtaining a copy of this software and associated documentation
5 # files (the "Software"), to deal in the Software without
6 # restriction, including without limitation the rights to use,
7 # copy, modify, merge, publish, distribute, sublicense, and/or sell
8 # copies of the Software, and to permit persons to whom the
9 # Software is furnished to do so, subject to the following
12 # The above copyright notice and this permission notice shall be
13 # included in all copies or substantial portions of the Software.
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17 # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 # OTHER DEALINGS IN THE SOFTWARE.
24 # The original code link is https://github.com/iamteem/redisco/tree/master/redisco/containers.py
27 This module contains the container classes to create objects
28 that persist directly in a Redis server.
32 from functools import partial
35 class Container(object):
36 """Create a container object saved in Redis.
39 key -- the Redis key this container is stored at
40 db -- the Redis client object. Default: None
42 When ``db`` is not set, the gets the default connection from
43 ``redisco.connection`` module.
46 def __init__(self, key, db=None, pipeline=None):
49 self.pipeline = pipeline
52 """Remove container from Redis database."""
55 def __getattribute__(self, att):
56 if att in object.__getattribute__(self, 'DELEGATEABLE_METHODS'):
57 return partial(getattr(object.__getattribute__(self, 'db'), att), self.key)
59 return object.__getattribute__(self, att)
67 if hasattr(self, 'db_cache') and self.db_cache:
70 from . import connection
71 self.db_cache = connection
74 DELEGATEABLE_METHODS = ()
77 class Hash(Container, collections.MutableMapping):
79 def __getitem__(self, att):
82 def __setitem__(self, att, val):
85 def __delitem__(self, att):
92 return self.hgetall().__iter__()
94 def __contains__(self, att):
95 return self.hexists(att)
98 return "<%s '%s' %s>" % (self.__class__.__name__, self.key, self.hgetall())
107 return self.hgetall()
109 def _set_dict(self, new_dict):
111 self.update(new_dict)
113 dict = property(_get_dict, _set_dict)
115 DELEGATEABLE_METHODS = ('hlen', 'hset', 'hdel', 'hkeys', 'hgetall', 'hvals',
116 'hget', 'hexists', 'hincrby', 'hmget', 'hmset')