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.

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