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.

225 lines
7.4 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. self._s.auth = lambda x: x # don't let requests add auth headers
  45. # retry once to reset connection with Keycloak after tomcat's ConnectionTimeout
  46. # see https://github.com/marcospereirampj/python-keycloak/issues/36
  47. for protocol in ('https://', 'http://'):
  48. adapter = HTTPAdapter(max_retries=1)
  49. # adds POST to retry whitelist
  50. method_whitelist = set(adapter.max_retries.method_whitelist)
  51. method_whitelist.add('POST')
  52. adapter.max_retries.method_whitelist = frozenset(method_whitelist)
  53. self._s.mount(protocol, adapter)
  54. def __del__(self):
  55. self._s.close()
  56. @property
  57. def base_url(self):
  58. """ Return base url in use for requests to the server. """
  59. return self._base_url
  60. @base_url.setter
  61. def base_url(self, value):
  62. """ """
  63. self._base_url = value
  64. @property
  65. def timeout(self):
  66. """ Return timeout in use for request to the server. """
  67. return self._timeout
  68. @timeout.setter
  69. def timeout(self, value):
  70. """ """
  71. self._timeout = value
  72. @property
  73. def verify(self):
  74. """ Return verify in use for request to the server. """
  75. return self._verify
  76. @verify.setter
  77. def verify(self, value):
  78. """ """
  79. self._verify = value
  80. @property
  81. def headers(self):
  82. """ Return header request to the server. """
  83. return self._headers
  84. @headers.setter
  85. def headers(self, value):
  86. """ """
  87. self._headers = value
  88. def param_headers(self, key):
  89. """ Return a specific header parameter.
  90. :arg
  91. key (str): Header parameters key.
  92. :return:
  93. If the header parameters exist, return its value.
  94. """
  95. return self.headers.get(key)
  96. def clean_headers(self):
  97. """ Clear header parameters. """
  98. self.headers = {}
  99. def exist_param_headers(self, key):
  100. """ Check if the parameter exists in the header.
  101. :arg
  102. key (str): Header parameters key.
  103. :return:
  104. If the header parameters exist, return True.
  105. """
  106. return self.param_headers(key) is not None
  107. def add_param_headers(self, key, value):
  108. """ Add a single parameter inside the header.
  109. :arg
  110. key (str): Header parameters key.
  111. value (str): Value to be added.
  112. """
  113. self.headers[key] = value
  114. def del_param_headers(self, key):
  115. """ Remove a specific parameter.
  116. :arg
  117. key (str): Key of the header parameters.
  118. """
  119. self.headers.pop(key, None)
  120. def raw_get(self, path, **kwargs):
  121. """ Submit get request to the path.
  122. :arg
  123. path (str): Path for request.
  124. :return
  125. Response the request.
  126. :exception
  127. HttpError: Can't connect to server.
  128. """
  129. try:
  130. return self._s.get(urljoin(self.base_url, path),
  131. params=kwargs,
  132. headers=self.headers,
  133. timeout=self.timeout,
  134. verify=self.verify)
  135. except Exception as e:
  136. raise KeycloakConnectionError(
  137. "Can't connect to server (%s)" % e)
  138. def raw_post(self, path, data, **kwargs):
  139. """ Submit post request to the path.
  140. :arg
  141. path (str): Path for request.
  142. data (dict): Payload for request.
  143. :return
  144. Response the request.
  145. :exception
  146. HttpError: Can't connect to server.
  147. """
  148. try:
  149. return self._s.post(urljoin(self.base_url, path),
  150. params=kwargs,
  151. data=data,
  152. headers=self.headers,
  153. timeout=self.timeout,
  154. verify=self.verify)
  155. except Exception as e:
  156. raise KeycloakConnectionError(
  157. "Can't connect to server (%s)" % e)
  158. def raw_put(self, path, data, **kwargs):
  159. """ Submit put request to the path.
  160. :arg
  161. path (str): Path for request.
  162. data (dict): Payload for request.
  163. :return
  164. Response the request.
  165. :exception
  166. HttpError: Can't connect to server.
  167. """
  168. try:
  169. return self._s.put(urljoin(self.base_url, path),
  170. params=kwargs,
  171. data=data,
  172. headers=self.headers,
  173. timeout=self.timeout,
  174. verify=self.verify)
  175. except Exception as e:
  176. raise KeycloakConnectionError(
  177. "Can't connect to server (%s)" % e)
  178. def raw_delete(self, path, data={}, **kwargs):
  179. """ Submit delete request to the path.
  180. :arg
  181. path (str): Path for request.
  182. data (dict): Payload for request.
  183. :return
  184. Response the request.
  185. :exception
  186. HttpError: Can't connect to server.
  187. """
  188. try:
  189. return self._s.delete(urljoin(self.base_url, path),
  190. params=kwargs,
  191. data=data,
  192. headers=self.headers,
  193. timeout=self.timeout,
  194. verify=self.verify)
  195. except Exception as e:
  196. raise KeycloakConnectionError(
  197. "Can't connect to server (%s)" % e)