You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

219 lines
7.2 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. try:
  24. from urllib.parse import urljoin
  25. except ImportError:
  26. from urlparse import urljoin
  27. import requests
  28. from requests.adapters import HTTPAdapter
  29. from .exceptions import (KeycloakConnectionError)
  30. class ConnectionManager(object):
  31. """ Represents a simple server connection.
  32. Args:
  33. base_url (str): The server URL.
  34. headers (dict): The header parameters of the requests to the server.
  35. timeout (int): Timeout to use for requests to the server.
  36. verify (bool): Verify server SSL.
  37. """
  38. def __init__(self, base_url, headers={}, timeout=60, verify=True):
  39. self._base_url = base_url
  40. self._headers = headers
  41. self._timeout = timeout
  42. self._verify = verify
  43. self._s = requests.Session()
  44. # retry once to reset connection with Keycloak after tomcat's ConnectionTimeout
  45. # see https://github.com/marcospereirampj/python-keycloak/issues/36
  46. for protocol in ('https://', 'http://'):
  47. adapter = HTTPAdapter(max_retries=1)
  48. # adds POST to retry whitelist
  49. method_whitelist = set(adapter.max_retries.method_whitelist)
  50. method_whitelist.add('POST')
  51. adapter.max_retries.method_whitelist = frozenset(method_whitelist)
  52. self._s.mount(protocol, adapter)
  53. @property
  54. def base_url(self):
  55. """ Return base url in use for requests to the server. """
  56. return self._base_url
  57. @base_url.setter
  58. def base_url(self, value):
  59. """ """
  60. self._base_url = value
  61. @property
  62. def timeout(self):
  63. """ Return timeout in use for request to the server. """
  64. return self._timeout
  65. @timeout.setter
  66. def timeout(self, value):
  67. """ """
  68. self._timeout = value
  69. @property
  70. def verify(self):
  71. """ Return verify in use for request to the server. """
  72. return self._verify
  73. @verify.setter
  74. def verify(self, value):
  75. """ """
  76. self._verify = value
  77. @property
  78. def headers(self):
  79. """ Return header request to the server. """
  80. return self._headers
  81. @headers.setter
  82. def headers(self, value):
  83. """ """
  84. self._headers = value
  85. def param_headers(self, key):
  86. """ Return a specific header parameter.
  87. :arg
  88. key (str): Header parameters key.
  89. :return:
  90. If the header parameters exist, return its value.
  91. """
  92. return self.headers.get(key)
  93. def clean_headers(self):
  94. """ Clear header parameters. """
  95. self.headers = {}
  96. def exist_param_headers(self, key):
  97. """ Check if the parameter exists in the header.
  98. :arg
  99. key (str): Header parameters key.
  100. :return:
  101. If the header parameters exist, return True.
  102. """
  103. return self.param_headers(key) is not None
  104. def add_param_headers(self, key, value):
  105. """ Add a single parameter inside the header.
  106. :arg
  107. key (str): Header parameters key.
  108. value (str): Value to be added.
  109. """
  110. self.headers[key] = value
  111. def del_param_headers(self, key):
  112. """ Remove a specific parameter.
  113. :arg
  114. key (str): Key of the header parameters.
  115. """
  116. self.headers.pop(key, None)
  117. def raw_get(self, path, **kwargs):
  118. """ Submit get request to the path.
  119. :arg
  120. path (str): Path for request.
  121. :return
  122. Response the request.
  123. :exception
  124. HttpError: Can't connect to server.
  125. """
  126. try:
  127. return self._s.get(urljoin(self.base_url, path),
  128. params=kwargs,
  129. headers=self.headers,
  130. timeout=self.timeout,
  131. verify=self.verify)
  132. except Exception as e:
  133. raise KeycloakConnectionError(
  134. "Can't connect to server (%s)" % e)
  135. def raw_post(self, path, data, **kwargs):
  136. """ Submit post request to the path.
  137. :arg
  138. path (str): Path for request.
  139. data (dict): Payload for request.
  140. :return
  141. Response the request.
  142. :exception
  143. HttpError: Can't connect to server.
  144. """
  145. try:
  146. return self._s.post(urljoin(self.base_url, path),
  147. params=kwargs,
  148. data=data,
  149. headers=self.headers,
  150. timeout=self.timeout,
  151. verify=self.verify)
  152. except Exception as e:
  153. raise KeycloakConnectionError(
  154. "Can't connect to server (%s)" % e)
  155. def raw_put(self, path, data, **kwargs):
  156. """ Submit put request to the path.
  157. :arg
  158. path (str): Path for request.
  159. data (dict): Payload for request.
  160. :return
  161. Response the request.
  162. :exception
  163. HttpError: Can't connect to server.
  164. """
  165. try:
  166. return self._s.put(urljoin(self.base_url, path),
  167. params=kwargs,
  168. data=data,
  169. headers=self.headers,
  170. timeout=self.timeout,
  171. verify=self.verify)
  172. except Exception as e:
  173. raise KeycloakConnectionError(
  174. "Can't connect to server (%s)" % e)
  175. def raw_delete(self, path, **kwargs):
  176. """ Submit delete request to the path.
  177. :arg
  178. path (str): Path for request.
  179. :return
  180. Response the request.
  181. :exception
  182. HttpError: Can't connect to server.
  183. """
  184. try:
  185. return self._s.delete(urljoin(self.base_url, path),
  186. params=kwargs,
  187. headers=self.headers,
  188. timeout=self.timeout,
  189. verify=self.verify)
  190. except Exception as e:
  191. raise KeycloakConnectionError(
  192. "Can't connect to server (%s)" % e)