doing some light relation-like stuff

although I spent way too much time on the server side since deciding
to add Redis as "persistence".
This commit is contained in:
Dan Buch 2012-05-18 11:18:41 -04:00
parent 28799b806f
commit bfc97737b4
11 changed files with 124 additions and 47 deletions

View File

@ -5,6 +5,10 @@ SITE = 'http://localhost:9282' unless defined?(SITE)
class Person < ActiveResource::Base
self.site = SITE
def family
Family.find(self.surname.downcase)
end
end
class Family < ActiveResource::Base

View File

@ -6,4 +6,4 @@ if [ $? -ne 0 ]; then
fi
cd $(dirname $(readlink -f $0))
export PYTHONPATH="$PWD:$PYTHONPATH"
exec aspen -w ./www -a '0.0.0.0:9282'
exec aspen --changes_reload=yes -w ./www -a '0.0.0.0:9282'

View File

@ -0,0 +1,15 @@
import redis
_MEMCACHE = {'pool': None}
def get_pool():
if not _MEMCACHE['pool']:
_MEMCACHE['pool'] = \
redis.ConnectionPool(host='localhost', port=6379, db=0)
return _MEMCACHE['pool']
def get_redis_conn():
return redis.Redis(connection_pool=get_pool())

12
ares/server/families.py Normal file
View File

@ -0,0 +1,12 @@
from server.resource import Resource
class Families(Resource):
__collection__ = 'families'
__required_keys__ = ('surname',)
def get_by_surname(self, surname):
for family in self.getall():
if family['surname'] == surname:
return family
return None

6
ares/server/people.py Normal file
View File

@ -0,0 +1,6 @@
from server.resource import Resource
class People(Resource):
__collection__ = 'people'
__required_keys__ = ('name', 'surname', 'age')

View File

@ -1,41 +0,0 @@
class Person(object):
_people = [
{
'name': {
'first': 'Hammy',
'last': 'Spammy',
},
'age': 42,
'id': 1,
},
{
'name': {
'first': 'Sampers',
'last': 'Dancer',
},
'age': 38,
'id': 2
},
]
def __init__(self):
self._index()
def _index(self):
self._people_by_id = dict(((p['id'], p) for p in self._people))
def getall(self):
return self._people
def get(self, person_id):
return self._people_by_id[person_id]
def add(self, person):
if None in (person.get('name'), person.get('age')):
raise ValueError('Missing required fields!: {}'.format(person))
person['id'] = len(self._people) + 1
self._people.append(person)
self._index()
return person['id']

46
ares/server/resource.py Normal file
View File

@ -0,0 +1,46 @@
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']

20
ares/www/families.json Normal file
View File

@ -0,0 +1,20 @@
import json
from server.families import Families
__families__ = Families()
if GET:
response.body = __families__.getall()
elif POST:
family = json.loads(
request.body.s_iter.read(int(request.headers['Content-Length']))
)['family']
family_id = __families__.add(family)
response.headers['Location'] = '/families/{}.json'.format(family_id)
family['id'] = family_id
response.body = family
response.code = 201
# vim:filetype=python

View File

@ -0,0 +1,10 @@
from server.families import Families
__families__ = Families()
family = __families__.get_by_surname(path['surname'])
if family:
response.body = {'family': family}
else:
response.code = 404
# vim:filetype=python

View File

@ -1,8 +1,8 @@
import json
from server.person import Person
from server.people import People
from aspen import Response
__people__ = Person()
__people__ = People()

View File

@ -1,6 +1,11 @@
from server.person import Person
__people__ = Person()
from server.people import People
__people__ = People()
response.body = {'person': __people__.get(int(path['id']))}
person = __people__.get(int(path['id']))
if person:
response.body = {'person': person}
else:
response.code = 404
# vim:filetype=python