Completed
Push — master ( f794c9...b22598 )
by Edward
19s
created

CloudflareBaseAction.send_user_error()   A

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import requests
17
18
from st2actions.runners.pythonrunner import Action
19
20
21
class CloudflareBaseAction(Action):
22
    def __init__(self, config):
23
        super(CloudflareBaseAction, self).__init__(config)
24
25
        self.session = requests.Session()
26
27
        try:
28
            self.api_host = self.config['api_host']
29
        except KeyError:
30
            raise ValueError("Missing api host in the config.")
31
32
    def send_user_error(self, message):
33
        """
34
        Prints an user error message.
35
        """
36
        print(message)
37
38
    def _get(self, url, headers, payload):
39
        """
40
        Issue a get request via requests.session()
41
42
        Args:
43
            url: The URL.
44
            headers: The Headers
45
            payload: The Payload.
46
47
        Returns:
48
            dict: Of JSON payload.
49
50
        Raises:
51
            ValueError: On HTTP error or Invalid JSON.
52
        """
53
54
        try:
55
            r = self.session.get(url,
56
                                 headers=headers,
57
                                 params=payload)
58
            r.raise_for_status()
59
        except requests.exceptions.HTTPError:
60
            raise ValueError("HTTP error: %s" % r.status_code)
61
62
        try:
63
            data = r.json()
64
        except:
65
            raise ValueError("Invalid JSON")
66
        else:
67
            return data
68