bfc97737b4
although I spent way too much time on the server side since deciding to add Redis as "persistence".
47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
import json
|
|
|
|
from server import get_redis_conn
|
|
|
|
|
|
class Resource(object):
|
|
__collection__ = 'generic'
|
|
__required_keys__ = ()
|
|
|
|
def __init__(self):
|
|
self._db = get_redis_conn()
|
|
|
|
def getall(self):
|
|
ret = []
|
|
|
|
for resource in self._db.hgetall(self.__collection__).itervalues():
|
|
try:
|
|
ret.append(json.loads(resource))
|
|
except ValueError, exc:
|
|
print_exc()
|
|
|
|
return ret
|
|
|
|
def get(self, resource_id):
|
|
raw_resource = self._db.hget(self.__collection__, resource_id)
|
|
|
|
if not raw_resource:
|
|
return None
|
|
|
|
resource = json.loads(raw_resource)
|
|
return resource
|
|
|
|
def add(self, resource_dict):
|
|
if None in (resource_dict.get(k) for k in self.__required_keys__):
|
|
raise ValueError(
|
|
'Missing required fields!: {}'.format(resource_dict)
|
|
)
|
|
|
|
resource_dict['id'] = self._db.incr(self.__collection__ + '_ids')
|
|
success = self._db.hset(
|
|
self.__collection__, resource_dict['id'], json.dumps(resource_dict)
|
|
)
|
|
assert success, 'Failed to save!'
|
|
|
|
return resource_dict['id']
|
|
|