Permalink
Browse files

finished the collection_ apis

  • Loading branch information...
1 parent b819d7b commit 72e7912de15081f39f8d495aedbae6d25129a58c @billrest billrest committed Jan 2, 2012
Showing with 115 additions and 18 deletions.
  1. +2 −2 cornicesqla/tests/example.py
  2. +35 −0 cornicesqla/tests/test_metadb.py
  3. +78 −16 cornicesqla/views.py
View
4 cornicesqla/tests/example.py
@@ -12,10 +12,10 @@ class UsersView(object):
collection_path = '/users'
session = DBSession
- def serialize(self, request):
+ def serialize(self):
"""Unserialize the data from the request."""
try:
- user = json.loads(request.body)
+ user = json.loads(self.request.body)
except ValueError:
request.errors.add('body', 'item', 'Bad Json data!')
# let's quit
View
35 cornicesqla/tests/test_metadb.py
@@ -44,3 +44,38 @@ def test_def(self):
user = json.loads(self.app.get('/users/1').body)
self.assertEqual(user['id'], 1)
self.assertEqual(user['name'], 'tarek2')
+
+ self.app.put('/users/2', params=json.dumps({'name': 'bill'}))
+
+ res = self.app.get('/users')
+ users = json.loads(res.body)
+ self.assertEqual(len(users['items']), 2)
+
+ # let's try some collection calls
+ bob = {'name': 'bob'}
+ sarah = {'name': 'sarah'}
+
+ res = self.app.put('/users', params=json.dumps([bob, sarah]))
+ res = json.loads(res.body)
+ self.assertEqual(res['ids'], [1, 2])
+
+ res = json.loads(self.app.delete('/users').body)
+ self.assertEqual(res['deleted'], 2)
+
+ res = self.app.put('/users', params=json.dumps([bob, sarah]))
+ res = json.loads(res.body)
+ self.assertEqual(res['ids'], [1, 2])
+
+ bill = {'name': 'bill'}
+ sarah = {'name': 'sarah2'}
+ res = self.app.post('/users', params=json.dumps([bill, sarah]))
+ res = json.loads(res.body)
+ self.assertEqual(res['ids'], [3, 4])
+
+ res = json.loads(self.app.get('/users/4').body)
+ self.assertEquals(res['name'], 'sarah2')
+
+ self.app.post('/users', params=json.dumps([bill]))
+
+ res = json.loads(self.app.get('/users').body)
+ self.assertEquals(len(res['items']), 5)
View
94 cornicesqla/views.py
@@ -14,7 +14,6 @@ def __new__(meta, name, bases, class_dict):
return klass
-# XXX 'id' is hardcoded for now
class DBView(object):
mapping = None
@@ -28,30 +27,94 @@ def __init__(self, request):
self.dbsession = self.session()
self.cols = self.mapping.__table__.c.keys()
- def collection_get(self):
- """Returns a collection of items."""
- # batch ?
- items = self.dbsession.query(self.mapping)
- return {'items': [item for item in items]}
-
- def serialize(self, request):
- """Unserialize the data from the request.
+ #
+ # Serialisation / deserialisation
+ #
+ def serialize(self):
+ """Serialize the data from the request.
Also, use the mapping to control that the data is valid
"""
try:
- return json.loads(request.body)
+ return json.loads(self.request.body)
except ValueError:
request.errors.append('body', 'item', 'Bad Json data!')
+ def collection_serialize(self):
+ """Serialize
+ """
+ try:
+ return json.loads(self.request.body)
+ except ValueError:
+ self.request.errors.add('body', 'item', 'Bad Json data!')
+
def deserialize(self, item):
output = {}
for key in self.cols:
output[key] = getattr(item, key)
return output
+ def collection_deserialize(self, items):
+ """ Deserialize a list
+ """
+ return [self.deserialize(item) for item in items]
+
+ #
+ # Collection management
+ #
+ def collection_get(self):
+ """Returns a collection of items.
+
+ XXX for now returns the full items
+ """
+ # batch ?
+ items = self.collection_deserialize(self.dbsession.query(self.mapping))
+ return {'items': items}
+
+ def _put_data(self, replace=False):
+ items = self.collection_serialize()
+ if len(self.request.errors) > 0:
+ return json_error(self.request.errors)
+
+ if replace:
+ # delete previous entries
+ self.dbsession.query(self.mapping).delete()
+
+ dbitems = []
+ for item in items:
+ item = self.mapping(**item)
+ self.dbsession.add(item)
+ dbitems.append(item)
+
+ self.dbsession.commit()
+ return {'ids': [item.id for item in dbitems]}
+
+ def collection_post(self):
+ """Create one or several new entries in the collection.
+
+ The new entries ids are assigned automatically and returned.
+ """
+ return self._put_data()
+
+ def collection_put(self):
+ """Replace the entire collection with the new items.
+
+ The new entries ids are assigned automatically and returned.
+ """
+ return self._put_data(replace=True)
+
+ def collection_delete(self):
+ """Deletes the entire collection.
+ """
+ # delete all entries
+ deleted = self.dbsession.query(self.mapping).delete()
+ return {'deleted': deleted}
+
+ #
+ # Item management
+ #
def put(self):
- """Updates or create an item."""
+ """Updates or creates an item."""
# grab the id
id_ = int(self.request.matchdict[self.match_key])
@@ -63,7 +126,7 @@ def put(self):
return self.post()
# we can update
- new_item = self.serialize(self.request)
+ new_item = self.serialize()
if len(self.request.errors) > 0:
return json_error(self.request.errors)
@@ -79,9 +142,9 @@ def put(self):
return {'status': 'OK'}
def post(self):
- """Puts an item"""
+ """Creates an item"""
# serialize the request into a PUT-able item
- item = self.serialize(self.request)
+ item = self.serialize()
if len(self.request.errors) > 0:
return json_error(self.request.errors)
@@ -95,7 +158,7 @@ def post(self):
try:
self.dbsession.commit() # needed ?
except IntegrityError, e:
- # that id is taken already,
+ # that id is taken already probably,
self.request.errors.add('body', 'item', e.message)
self.dbsession.rollback()
return json_error(self.request.errors)
@@ -117,7 +180,6 @@ def delete(self):
"""Deletes one item"""
id_ = int(self.request.matchdict[self.match_key])
item = self.dbsession.query(self.mapping)
- # catch issue if object does not exist then 404 XXX
deleted = item.filter(self.mapping.id==id_).delete()
if deleted == 0:
self.request.matchdict = None # for cornice

0 comments on commit 72e7912

Please sign in to comment.