Total Complexity | 8 |
Total Lines | 39 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import requests |
||
8 | class ActiveCampaignAction(Action): |
||
9 | |||
10 | def run(self, **kwargs): |
||
11 | if kwargs['api_key'] is None: |
||
12 | kwargs['api_key'] = self.config['api_key'] |
||
13 | |||
14 | return self._get_request(kwargs) |
||
15 | |||
16 | def _get_request(self, params): |
||
17 | url = urlparse.urljoin(self.config['url'], 'admin/api.php') |
||
18 | headers = {} |
||
19 | headers['Content-Type'] = 'application/x-www-form-urlencoded' |
||
20 | |||
21 | params = self._format_params(params) |
||
22 | data = urllib.urlencode(params) |
||
23 | response = requests.get(url=url, |
||
24 | headers=headers, params=data) |
||
25 | |||
26 | results = response.json() |
||
27 | if results['result_code'] is not 1: |
||
28 | failure_reason = ('Failed to perform action: %s \ |
||
29 | (status code: %s)' % (response.text, |
||
30 | response.status_code)) |
||
31 | self.logger.exception(failure_reason) |
||
32 | raise Exception(failure_reason) |
||
33 | |||
34 | return results |
||
35 | |||
36 | def _format_params(self, params): |
||
37 | output = {} |
||
38 | for k, v in params.iteritems(): |
||
39 | if isinstance(v, dict): |
||
40 | for pk, pv in v.iteritems(): |
||
41 | param_name = "%s[%s]" % (k, pk) |
||
42 | output[param_name] = pv |
||
43 | else: |
||
44 | output[k] = v |
||
45 | return output |
||
46 |