summaryrefslogtreecommitdiffstats
path: root/wcs_es/wcs_api.py
blob: f14ba1e0194f64240ead41a029c064bc7840474c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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')]