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.

224 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
  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. """
  32. Represents a simple server connection.
  33. :param base_url: (str) The server URL.
  34. :param headers: (dict) The header parameters of the requests to the server.
  35. :param timeout: (int) Timeout to use for requests to the server.
  36. :param verify: (bool) Verify server SSL.
  37. :param proxies: (dict) The proxies servers requests is sent by.
  38. """
  39. def __init__(self, base_url, headers={}, timeout=60, verify=True, proxies=None):
  40. self._base_url = base_url
  41. self._headers = headers
  42. self._timeout = timeout
  43. self._verify = verify
  44. self._s = requests.Session()
  45. self._s.auth = lambda x: x # don't let requests add auth headers
  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. if proxies:
  56. self._s.proxies.update(proxies)
  57. def __del__(self):
  58. self._s.close()
  59. @property
  60. def base_url(self):
  61. """Return base url in use for requests to the server."""
  62. return self._base_url
  63. @base_url.setter
  64. def base_url(self, value):
  65. """ """
  66. self._base_url = value
  67. @property
  68. def timeout(self):
  69. """Return timeout in use for request to the server."""
  70. return self._timeout
  71. @timeout.setter
  72. def timeout(self, value):
  73. """ """
  74. self._timeout = value
  75. @property
  76. def verify(self):
  77. """Return verify in use for request to the server."""
  78. return self._verify
  79. @verify.setter
  80. def verify(self, value):
  81. """ """
  82. self._verify = value
  83. @property
  84. def headers(self):
  85. """Return header request to the server."""
  86. return self._headers
  87. @headers.setter
  88. def headers(self, value):
  89. """ """
  90. self._headers = value
  91. def param_headers(self, key):
  92. """
  93. Return a specific header parameter.
  94. :param key: (str) Header parameters key.
  95. :returns: If the header parameters exist, return its value.
  96. """
  97. return self.headers.get(key)
  98. def clean_headers(self):
  99. """Clear header parameters."""
  100. self.headers = {}
  101. def exist_param_headers(self, key):
  102. """Check if the parameter exists in the header.
  103. :param key: (str) Header parameters key.
  104. :returns: 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. :param key: (str) Header parameters key.
  110. :param value: (str) Value to be added.
  111. """
  112. self.headers[key] = value
  113. def del_param_headers(self, key):
  114. """Remove a specific parameter.
  115. :param key: (str) Key of the header parameters.
  116. """
  117. self.headers.pop(key, None)
  118. def raw_get(self, path, **kwargs):
  119. """Submit get request to the path.
  120. :param path: (str) Path for request.
  121. :returns: Response the request.
  122. :raises: HttpError Can't connect to server.
  123. """
  124. try:
  125. return self._s.get(
  126. urljoin(self.base_url, path),
  127. params=kwargs,
  128. headers=self.headers,
  129. timeout=self.timeout,
  130. verify=self.verify,
  131. )
  132. except Exception as e:
  133. raise KeycloakConnectionError("Can't connect to server (%s)" % e)
  134. def raw_post(self, path, data, **kwargs):
  135. """Submit post request to the path.
  136. :param path: (str) Path for request.
  137. :param data: (dict) Payload for request.
  138. :returns: Response the request.
  139. :raises: HttpError Can't connect to server.
  140. """
  141. try:
  142. return self._s.post(
  143. urljoin(self.base_url, path),
  144. params=kwargs,
  145. data=data,
  146. headers=self.headers,
  147. timeout=self.timeout,
  148. verify=self.verify,
  149. )
  150. except Exception as e:
  151. raise KeycloakConnectionError("Can't connect to server (%s)" % e)
  152. def raw_put(self, path, data, **kwargs):
  153. """Submit put request to the path.
  154. :param path: (str) Path for request.
  155. :param data: (dict) Payload for request.
  156. :returns: Response the request.
  157. :raises: HttpError Can't connect to server.
  158. """
  159. try:
  160. return self._s.put(
  161. urljoin(self.base_url, path),
  162. params=kwargs,
  163. data=data,
  164. headers=self.headers,
  165. timeout=self.timeout,
  166. verify=self.verify,
  167. )
  168. except Exception as e:
  169. raise KeycloakConnectionError("Can't connect to server (%s)" % e)
  170. def raw_delete(self, path, data={}, **kwargs):
  171. """Submit delete request to the path.
  172. :param path: (str) Path for request.
  173. :param data: (dict) Payload for request.
  174. :returns: Response the request.
  175. :raises: HttpError Can't connect to server.
  176. """
  177. try:
  178. return self._s.delete(
  179. urljoin(self.base_url, path),
  180. params=kwargs,
  181. data=data,
  182. headers=self.headers,
  183. timeout=self.timeout,
  184. verify=self.verify,
  185. )
  186. except Exception as e:
  187. raise KeycloakConnectionError("Can't connect to server (%s)" % e)