Completed
Push — master ( e63902...8a80a2 )
by dotzero
02:21
created

BaseResource.__init__()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 5
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 9.4285
1
# -*- coding: utf-8 -*-
2
#
3
# Copyright (c) 2016 dotzero <[email protected]>
4
#
5
# Permission is hereby granted, free of charge, to any person obtaining a copy
6
# of this software and associated documentation files (the "Software"), to deal
7
# in the Software without restriction, including without limitation the rights
8
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
# copies of the Software, and to permit persons to whom the Software is
10
# furnished to do so, subject to the following conditions:
11
#
12
# The above copyright notice and this permission notice shall be included
13
# in all copies or substantial portions of the Software.
14
#
15
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
# SOFTWARE.
22
23 1
import sys
24 1
import json
25 1
import logging
26 1
from .errors import ApiHandlerError
27
28 1
try:
29
    # python3
30 1
    from urllib.request import build_opener, Request, HTTPHandler
31
    from urllib.error import HTTPError
32
    from urllib.parse import urlencode
33
except ImportError:  # pragma: no cover
34
    # python2
35
    from urllib2 import build_opener, Request, HTTPHandler, HTTPError
36
    from urllib import urlencode
37
38 1
log = logging.getLogger(__name__)
39
40 1
POST_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'
41
42
43 1
class BaseResource(object):
44 1
    def __init__(self, auth=None):
45 1
        if auth is None:
46
            raise ApiHandlerError('Auth handler is not defined')
47
48 1
        self._auth = auth
49
50 1
    def _request(self, url, method='GET', data=None):
51 1
        url = self._auth.get_request_endpoint() + url
52 1
        headers = self._auth.get_request_headers()
53
54 1
        if data is not None:
55 1
            data = urlencode(data)
56 1
            if method in ['GET', 'DELETE']:
57 1
                url = url + '?' + data
58 1
                data = None
59
            else:
60 1
                headers.update({'Content-Type': POST_CONTENT_TYPE})
61 1
                if sys.version_info > (3,):  # python3
62
                    data = data.encode('utf-8')
63
64 1
        log.debug(method + ' ' + url)
65 1
        log.debug(data)
66
67 1
        try:
68 1
            opener = build_opener(HTTPHandler)
69 1
            request = Request(url, data=data, headers=headers)
70 1
            request.get_method = lambda: method
71 1
            response = opener.open(request).read()
72 1
            data = self._parse_response(response)
73
        except HTTPError as e:
74
            log.error(e)
75
            data = self._parse_response(e.read())
76
            raise ApiHandlerError('Invalid server response', data)
77
        except ValueError as e:
78
            log.error(e)
79
            raise ApiHandlerError('Invalid server response')
80
81 1
        return data
82
83 1
    @staticmethod
84
    def _parse_response(response):
85 1
        try:
86 1
            return json.loads(response.decode('utf-8'))
87
        except ValueError:
88
            return False
89