summaryrefslogtreecommitdiffstats
path: root/wcs_es/wcs_api.py
diff options
context:
space:
mode:
Diffstat (limited to 'wcs_es/wcs_api.py')
-rw-r--r--wcs_es/wcs_api.py96
1 files changed, 96 insertions, 0 deletions
diff --git a/wcs_es/wcs_api.py b/wcs_es/wcs_api.py
new file mode 100644
index 0000000..f14ba1e
--- /dev/null
+++ b/wcs_es/wcs_api.py
@@ -0,0 +1,96 @@
+import requests
+import urlparse
+import urllib
+
+from . import signature
+
+class WcsApiError(Exception):
+ pass
+
+
+class BaseObject(object):
+ def __init__(self, wcs_api, **kwargs):
+ self.__wcs_api = wcs_api
+ self.__dict__.update(**kwargs)
+
+ def json(self):
+ d = self.__dict__.copy()
+ for key in d.keys():
+ if key.startswith('_'):
+ del d[key]
+ return d
+
+
+class FormData(BaseObject):
+ def json(self):
+ d = super(FormData, self).json()
+ formdef = d.pop('formdef')
+ d['formdef_slug'] = formdef.slug
+ return d
+
+ def __repr__(self):
+ return '<{klass} {display_id!r}>'.format(klass=self.__class__.__name__,
+ display_id=self.id)
+
+class FormDef(BaseObject):
+ def __init__(self, wcs_api, **kwargs):
+ self.__wcs_api = wcs_api
+ self.__dict__.update(**kwargs)
+
+ def __unicode__(self):
+ return self.title
+
+ @property
+ def datas(self):
+ datas = self.__wcs_api.get_formdata(self.slug)
+ for data in datas:
+ data.formdef = self
+ return datas
+
+ def __repr__(self):
+ return '<{klass} {slug!r}>'.format(klass=self.__class__.__name__, slug=self.slug)
+
+
+class WcsApi(object):
+ def __init__(self, url, orig, key, name_id=None, email=None, verify=False):
+ self.url = url
+ self.orig = orig
+ self.key = key
+ self.email = email
+ self.name_id = name_id
+ self.verify = verify
+
+ @property
+ def formdefs_url(self):
+ return urlparse.urljoin(self.url, 'api/formdefs/')
+
+ @property
+ def forms_url(self):
+ return urlparse.urljoin(self.url, 'api/forms/')
+
+ def get_json(self, *url_parts):
+ url = reduce(lambda x, y: urlparse.urljoin(x, y), url_parts)
+ params = {'orig': self.orig}
+ if self.email:
+ params['email'] = self.email
+ if self.name_id:
+ params['NameID'] = self.name_id
+ query_string = urllib.urlencode(params)
+ presigned_url = url + ('&' if '?' in url else '?') + query_string
+ signed_url = signature.sign_url(presigned_url, self.key)
+ try:
+ response = requests.get(signed_url, verify=False)
+ except requests.RequestException, e:
+ raise WcsApiError('GET request failed', signed_url, e)
+ else:
+ try:
+ return response.json()
+ except ValueError, e:
+ raise WcsApiError('Invalid JSON content', signed_url, e)
+
+ def get_formdefs(self):
+ return [FormDef(wcs_api=self, **d) for d in self.get_json(self.formdefs_url)]
+
+ def get_formdata(self, slug):
+ return [FormData(wcs_api=self, **d) for d in self.get_json(self.forms_url, slug + '/',
+ 'list?full=on')]