Completed
Push — master ( 32acac...19ae40 )
by Lakshmi
11:34
created

OctopusDeployAction   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 10
c 0
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A _init_client() 0 5 1
A make_post_request() 0 7 2
A __init__() 0 3 1
A _build_uri() 0 5 2
A make_get_request() 0 8 2
1
try:
2
    import requests
3
except ImportError:
4
    message = ('Missing "requests", please install it using pip:\n'
5
               'pip install requests')
6
    raise ImportError(message)
7
8
try:
9
    import json
10
except ImportError:
11
    message = ('Missing "json", please install it using pip:\n'
12
               'pip install json')
13
    raise ImportError(message)
14
15
from octopus_error import OctopusError
16
from st2actions.runners.pythonrunner import Action
17
18
__all__ = [
19
    'OctopusDeployAction',
20
]
21
22
23
class OctopusDeployAction(Action):
24
    def __init__(self, config):
25
        super(OctopusDeployAction, self).__init__(config)
26
        self.client = self._init_client()
27
28
    def _init_client(self):
29
        api_key = self.config['api_key']
30
        host = self.config['host']
31
        port = self.config['port']
32
        return OctopusDeployClient(api_key=api_key, host=host, port=port)
33
34
    def _build_uri(self):
35
        # big assumption but it'll cover 99% case,
36
        # as octopus runs https by default
37
        start = "http://" if self.client.port is 80 else "https://"
38
        return start + self.client.host + ":" + str(self.client.port) + "/api/"
39
40
    def make_post_request(self, action, payload):
41
        response = requests.post(self._build_uri() + action,
42
                                 data=json.dumps(payload), verify=False,
43
                                 headers=self.client.headers)
44
        if response.status_code != 200:
45
            raise OctopusError(response.text, response.status_code)
46
        return response.json()
47
48
    def make_get_request(self, action, params=None):
49
        response = requests.get(self._build_uri() + action,
50
                                verify=False,
51
                                params=params,
52
                                headers=self.client.headers)
53
        if response.status_code != 200:
54
            raise OctopusError(response.text, response.status_code)
55
        return response.json()
56
57
58
class OctopusDeployClient(object):
59
    def __init__(self, api_key, host, port):
60
        self.api_key = api_key
61
        self.host = host
62
        self.port = port
63
        self.headers = {'X-Octopus-ApiKey': self.api_key,
64
                        'Content-type': 'application/json',
65
                        'Accept': 'text/plain'}
66