Created
November 8, 2012 19:16
-
-
Save anonymous/4040895 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ModelProxy(object): | |
""" | |
Acts as a shim between the storage mechanism and our models. | |
""" | |
def __init__(self, instance, feature, path=''): | |
self.feature = feature | |
self.path = path | |
self.coll = DB[self.feature] | |
self.instance = instance | |
def get(self, key, default_value=None): | |
return self.__getitem__(key) or default_value | |
def exists(self, list_of_keys): | |
""" | |
Given a lsit of keys, return the ones that exist. | |
""" | |
key_map = {} | |
for key in list_of_keys: | |
parts = self.path.split('//') | |
parts.append(key) | |
hashed_key = ''.join([hashlib.sha1(p).hexdigest() for p in parts]) | |
key_map[hashed_key] = key | |
results = self.coll.find({'key':{'$in':key_map.keys()}}) | |
existing = [] | |
for result in results: | |
existing.append(key_map[result['key']]) | |
return existing | |
def construct_and_query(self, pairs): | |
""" | |
Given a lsit of pairs, create keys from each pair and return the value for each that exists. | |
""" | |
keys = [] | |
for pair in pairs: | |
parts = self.path.split('//') | |
parts.extend(pair) | |
hashed_key = ''.join([hashlib.sha1(p).hexdigest() for p in parts]) | |
keys.append(hashed_key) | |
return self.coll.find({'key':{'$in':keys}}) | |
def value(self): | |
try: | |
return self.instance.query_cache[self.feature+self.path] | |
except: | |
pass | |
parts = self.path.split('//') | |
key = ''.join([hashlib.sha1(p).hexdigest() for p in parts]) | |
item = self.coll.find_one({'key':key}) | |
if item: | |
self.instance.query_cache[self.feature+self.path]=item['value'] | |
return item['value'] | |
return None | |
def has_key(self, key): | |
obj = self.__getitem__(key).value() | |
return obj != None | |
def __nonzero__(self): | |
return bool(self.value()) | |
def __len__(self): | |
value = self.value() | |
if isinstance(value, list): | |
return len(value) | |
return 0 | |
def __float__(self): | |
return float(self.value()) | |
def index(self, value): | |
return self.value()[value] | |
def __getitem__(self, key): | |
""" | |
Return a ModelProxy with its path set properly. | |
""" | |
if self.path: | |
path = self.path + '//' + key | |
else: | |
path = key | |
return ModelProxy(self.instance, self.feature, path=path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment