[hooks] Abstract error handling during CKAN POST requests in a function
authorDenis Laxalde <denis.laxalde@logilab.fr>
Mon, 20 Oct 2014 16:05:36 +0200
changeset 12 183145b6bee7
parent 7 6e1d41bacacf
child 13 133dda956327
[hooks] Abstract error handling during CKAN POST requests in a function
hooks.py
--- a/hooks.py	Fri Oct 17 10:39:50 2014 +0200
+++ b/hooks.py	Mon Oct 20 16:05:36 2014 +0200
@@ -26,33 +26,32 @@
                                      ckan_instance_configured)
 
 
+def _ckan_action(config, eid, action, data=None):
+    """Run `ckan_post` and eventually raise ValidationError."""
+    try:
+        return ckan_post(config, action, data=data)
+    except (CKANPostError, RequestException) as exc:
+        raise ValidationError(eid, {'ckan_dataset_id': unicode(exc)})
+
+
 def create_dataset(config, eid, data):
     """Create a CKAN dataset and set `ckan_dataset_id` attribute or
     respective entity. Return the dataset id.
     """
-    try:
-        res = ckan_post(config, 'package_create', data)
-        return res['id']
-    except (CKANPostError, RequestException) as exc:
-        raise ValidationError(eid, {'ckan_dataset_id': unicode(exc)})
+    res = _ckan_action(config, eid, 'package_create', data)
+    return res['id']
 
 
 def update_dataset(config, eid, datasetid, udata):
     """Update an existing CKAN dataset"""
-    try:
-        data = ckan_post(config, 'package_show', {'id': datasetid})
-        data.update(udata)
-        ckan_post(config, 'package_update', data)
-    except (CKANPostError, RequestException) as exc:
-        raise ValidationError(eid, {'ckan_dataset_id': unicode(exc)})
+    data = _ckan_action(config, eid, 'package_show', data={'id': datasetid})
+    data.update(udata)
+    _ckan_action(config, eid, 'package_update', data=data)
 
 
 def delete_dataset(config, eid, datasetid):
     """Delete a CKAN dataset"""
-    try:
-        ckan_post(config, 'package_delete', {'id': datasetid})
-    except (CKANPostError, RequestException) as exc:
-        raise ValidationError(eid, {'ckan_dataset_id': unicode(exc)})
+    _ckan_action(config, eid, 'package_delete', data={'id': datasetid})
 
 
 class DeleteCKANDataSetHook(hook.Hook):