source: ogAgent-Git/src/opengnsys/RESTApi.py @ 324ffda

configure-ptt-chedecorare-oglive-methodsejecutarscript-b64fix-cfg2objfixes-winlgromero-filebeatmainno-ptt-paramogcore1oglogoglog2override-moduleping1ping2ping3ping4report-progresstls
Last change on this file since 324ffda was ecee987, checked in by Natalia Serrano <natalia.serrano@…>, 8 months ago

refs #702 have RESTApi.py handle errors and non-json responses

  • Property mode set to 100644
File size: 6.7 KB
Line 
1# -*- coding: utf-8 -*-
2#
3# Copyright (c) 201 Virtual Cable S.L.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without modification,
7# are permitted provided that the following conditions are met:
8#
9#    * Redistributions of source code must retain the above copyright notice,
10#      this list of conditions and the following disclaimer.
11#    * Redistributions in binary form must reproduce the above copyright notice,
12#      this list of conditions and the following disclaimer in the documentation
13#      and/or other materials provided with the distribution.
14#    * Neither the name of Virtual Cable S.L. nor the names of its contributors
15#      may be used to endorse or promote products derived from this software
16#      without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29"""
30@author: Adolfo Gómez, dkmaster at dkmon dot com
31"""
32
33# pylint: disable-msg=E1101,W0703
34
35
36
37import requests
38import logging
39import json
40import warnings
41
42from .log import logger
43
44from .utils import exceptionToMessage
45
46VERIFY_CERT = False  # Do not check server certificate
47TIMEOUT = 5  # Connection timout, in seconds
48
49
50class RESTError(Exception):
51    ERRCODE = 0
52
53
54class ConnectionError(RESTError):
55    ERRCODE = -1
56
57
58# Disable warnings log messages
59try:
60    import urllib3  # @UnusedImport
61except Exception:
62    from requests.packages import urllib3  # @Reimport
63
64try:
65    urllib3.disable_warnings()  # @UndefinedVariable
66    warnings.simplefilter("ignore")
67except Exception:
68    pass  # In fact, isn't too important, but wil log warns to logging file
69
70
71class REST(object):
72    """
73    Simple interface to remote REST apis.
74    The constructor expects the "base url" as parameter, that is, the url that will be common on all REST requests
75    Remember that this is a helper for "easy of use". You can provide your owns using requests lib for example.
76    Examples:
77       v = REST('https://example.com/rest/v1/') (Can omit trailing / if desired)
78       v.sendMessage('hello?param1=1&param2=2')
79         This will generate a GET message to https://example.com/rest/v1/hello?param1=1&param2=2, and return the
80         deserialized JSON result or an exception
81       v.sendMessage('hello?param1=1&param2=2', {'name': 'mario' })
82         This will generate a POST message to https://example.com/rest/v1/hello?param1=1&param2=2, with json encoded
83         body {'name': 'mario' }, and also returns
84         the deserialized JSON result or raises an exception in case of error
85    """
86
87    def __init__(self, url):
88        """
89        Initializes the REST helper
90        url is the full url of the REST API Base, as for example "https://example.com/rest/v1".
91        @param url The url of the REST API Base. The trailing '/' can be included or omitted, as desired.
92        """
93        self.endpoint = url
94
95        if self.endpoint[-1] != '/':
96            self.endpoint += '/'
97
98        # Some OSs ships very old python requests lib implementations, workaround them...
99        try:
100            self.newerRequestLib = requests.__version__.split('.')[0] >= '1'
101        except Exception:
102            self.newerRequestLib = False  # I no version, guess this must be an old requests
103
104        # Disable logging requests messages except for errors, ...
105        logging.getLogger("requests").setLevel(logging.CRITICAL)
106        # Tries to disable all warnings
107        try:
108            warnings.simplefilter("ignore")  # Disables all warnings
109        except Exception:
110            pass
111
112    def _getUrl(self, method):
113        """
114        Internal method
115        Composes the URL based on "method"
116        @param method: Method to append to base url for composition
117        """
118        url = self.endpoint + method
119
120        return url
121
122    def _request(self, url, data=None):
123        """
124        Launches the request
125        @param url: The url to obtain
126        @param data: if None, the request will be sent as a GET request. If != None, the request will be sent as a POST,
127        with data serialized as JSON in the body.
128        """
129        try:
130            if data is None:
131                logger.debug('Requesting using GET (no data provided) {}'.format(url))
132                # Old requests version does not support verify, but it do not checks ssl certificate by default
133                if self.newerRequestLib:
134                    r = requests.get(url, verify=VERIFY_CERT, timeout=TIMEOUT)
135                else:
136                    r = requests.get(url)
137            else:  # POST
138                logger.debug('Requesting using POST {}, data: {}'.format(url, data))
139                if self.newerRequestLib:
140                    r = requests.post(url, data=data, headers={'content-type': 'application/json'},
141                                      verify=VERIFY_CERT, timeout=TIMEOUT)
142                else:
143                    r = requests.post(url, data=data, headers={'content-type': 'application/json'})
144
145            r.raise_for_status()
146            ct = r.headers['Content-Type']
147            if 'application/json' != ct:
148                raise Exception (f'response content-type is not "application/json" but "{ct}"')
149            r = json.loads(r.content)  # Using instead of r.json() to make compatible with old requests lib versions
150        except requests.exceptions.RequestException as e:
151            raise ConnectionError(e)
152        except Exception as e:
153            raise ConnectionError(exceptionToMessage(e))
154
155        return r
156
157    def sendMessage(self, msg, data=None, processData=True):
158        """
159        Sends a message to remote REST server
160        @param data: if None or omitted, message will be a GET, else it will send a POST
161        @param processData: if True, data will be serialized to json before sending, else, data will be sent as "raw"
162        """
163        logger.debug('Invoking post message {} with data {}'.format(msg, data))
164
165        if processData and data is not None:
166            data = json.dumps(data)
167
168        url = self._getUrl(msg)
169        logger.debug('Requesting {}'.format(url))
170
171        return self._request(url, data)
Note: See TracBrowser for help on using the repository browser.