source: ogAgent-Git/src/opengnsys/RESTApi.py

qndtest
Last change on this file was 03a1cb2, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#877: OGAgent can connect to an alternate server, and fixing some Python code cleanup.

  • Property mode set to 100644
File size: 6.5 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
35from __future__ import unicode_literals
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 = json.loads(r.content)  # Using instead of r.json() to make compatible with old requests lib versions
146        except requests.exceptions.RequestException as e:
147            raise ConnectionError(e)
148        except Exception as e:
149            raise ConnectionError(exceptionToMessage(e))
150
151        return r
152
153    def sendMessage(self, msg, data=None, processData=True):
154        """
155        Sends a message to remote REST server
156        @param data: if None or omitted, message will be a GET, else it will send a POST
157        @param processData: if True, data will be serialized to json before sending, else, data will be sent as "raw"
158        """
159        logger.debug('Invoking post message {} with data {}'.format(msg, data))
160
161        if processData and data is not None:
162            data = json.dumps(data)
163
164        url = self._getUrl(msg)
165        logger.debug('Requesting {}'.format(url))
166
167        return self._request(url, data)
Note: See TracBrowser for help on using the repository browser.