Re-org folders, onboard test folder, test config
[optf/osdf.git] / osdf / utils / interfaces.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   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 # -------------------------------------------------------------------------
17 #
18
19 import requests
20
21 from osdf.config.base import osdf_config, creds_prefixes
22 from osdf.logging.osdf_logging import MH, debug_log
23
24
25 def get_rest_client(request_json, service):
26     """Get a RestClient based on request_json's callback URL and osdf_config's credentials based on service name
27     :param request_json:
28     :param service: so or cm
29     :return: rc -- RestClient
30     """
31     callback_url = request_json["requestInfo"]["callbackUrl"]
32     prefix = creds_prefixes[service]
33     config = osdf_config.deployment
34     c_userid, c_passwd = config[prefix + "Username"], config[prefix + "Password"]
35     return RestClient(url=callback_url, userid=c_userid, passwd=c_passwd)
36
37
38 class RestClient(object):
39     """Simple REST Client that supports get/post and basic auth"""
40
41     def __init__(self, userid=None, passwd=None, log_func=None, url=None, timeout=None, headers=None,
42                  method="POST", req_id=None):
43         self.auth = (userid, passwd) if userid and passwd else None
44         self.headers = headers if headers else {}
45         self.method = method
46         self.url = url
47         self.log_func = log_func
48         self.timeout = (30, 90) if timeout is None else timeout
49         self.req_id = req_id
50
51     def add_headers(self, headers):
52         self.headers.update(headers)
53
54     def request(self, url=None, method=None, asjson=True, ok_codes=(2, ),
55                 raw_response=False, noresponse=False, timeout=None, **kwargs):
56         """
57         :param url: REST end point to query
58         :param method: GET or POST (default is None => self.method)
59         :param asjson: whether the expected response is in json format
60         :param ok_codes: expected codes (prefix matching -- e.g. can be (20, 21, 32) or (2, 3))
61         :param noresponse: If no response is expected (as long as response codes are OK)
62         :param raw_response: If we need just the raw response (e.g. conductor sends transaction IDs in headers)
63         :param timeout: Connection and read timeouts
64         :param kwargs: Other parameters
65         :return:
66         """
67         if not self.req_id:
68             debug_log.debug("Requesting URL: {}".format(url or self.url))
69         else:
70             debug_log.debug("Requesting URL: {} for request ID: {}".format(url or self.url, self.req_id))
71
72         res = requests.request(url=url or self.url, method=method or self.method,
73                                auth=self.auth, headers=self.headers,
74                                timeout=timeout or self.timeout, **kwargs)
75
76         if self.log_func:
77             self.log_func(MH.received_http_response(res))
78
79         res_code = str(res.status_code)
80         if not any(res_code.startswith(x) for x in map(str, ok_codes)):
81             raise res.raise_for_status()
82
83         if raw_response:
84             return res
85         elif noresponse:
86             return None
87         elif asjson:
88             return res.json()
89         else:
90             return res.content