2
0

compat.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright 2012-2014 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import copy
  14. import datetime
  15. import sys
  16. import inspect
  17. import warnings
  18. import hashlib
  19. import logging
  20. import yaml
  21. from kscore.vendored import six
  22. from kscore.exceptions import MD5UnavailableError
  23. from kscore.vendored.requests.packages.urllib3 import exceptions
  24. logger = logging.getLogger(__name__)
  25. if six.PY3:
  26. from six.moves import http_client
  27. class HTTPHeaders(http_client.HTTPMessage):
  28. pass
  29. from urllib.parse import quote
  30. from urllib.parse import urlencode
  31. from urllib.parse import unquote
  32. from urllib.parse import unquote_plus
  33. from urllib.parse import urlparse
  34. from urllib.parse import urlsplit
  35. from urllib.parse import urlunsplit
  36. from urllib.parse import urljoin
  37. from urllib.parse import parse_qsl
  38. from urllib.parse import parse_qs
  39. from http.client import HTTPResponse
  40. from io import IOBase as _IOBase
  41. from base64 import encodebytes
  42. from email.utils import formatdate
  43. from itertools import zip_longest
  44. file_type = _IOBase
  45. zip = zip
  46. # In python3, unquote takes a str() object, url decodes it,
  47. # then takes the bytestring and decodes it to utf-8.
  48. # Python2 we'll have to do this ourself (see below).
  49. unquote_str = unquote_plus
  50. def set_socket_timeout(http_response, timeout):
  51. """Set the timeout of the socket from an HTTPResponse.
  52. :param http_response: An instance of ``httplib.HTTPResponse``
  53. """
  54. http_response._fp.fp.raw._sock.settimeout(timeout)
  55. def accepts_kwargs(func):
  56. # In python3.4.1, there's backwards incompatible
  57. # changes when using getargspec with functools.partials.
  58. return inspect.getfullargspec(func)[2]
  59. def ensure_unicode(s, encoding=None, errors=None):
  60. # NOOP in Python 3, because every string is already unicode
  61. return s
  62. def ensure_bytes(s, encoding='utf-8', errors='strict'):
  63. if isinstance(s, str):
  64. return s.encode(encoding, errors)
  65. if isinstance(s, bytes):
  66. return s
  67. raise ValueError("Expected str or bytes, received %s." % type(s))
  68. else:
  69. from urllib import quote
  70. from urllib import urlencode
  71. from urllib import unquote
  72. from urllib import unquote_plus
  73. from urlparse import urlparse
  74. from urlparse import urlsplit
  75. from urlparse import urlunsplit
  76. from urlparse import urljoin
  77. from urlparse import parse_qsl
  78. from urlparse import parse_qs
  79. from email.message import Message
  80. from email.Utils import formatdate
  81. file_type = file
  82. from itertools import izip as zip
  83. from itertools import izip_longest as zip_longest
  84. from httplib import HTTPResponse
  85. from base64 import encodestring as encodebytes
  86. class HTTPHeaders(Message):
  87. # The __iter__ method is not available in python2.x, so we have
  88. # to port the py3 version.
  89. def __iter__(self):
  90. for field, value in self._headers:
  91. yield field
  92. def unquote_str(value, encoding='utf-8'):
  93. # In python2, unquote() gives us a string back that has the urldecoded
  94. # bits, but not the unicode parts. We need to decode this manually.
  95. # unquote has special logic in which if it receives a unicode object it
  96. # will decode it to latin1. This is hard coded. To avoid this, we'll
  97. # encode the string with the passed in encoding before trying to
  98. # unquote it.
  99. byte_string = value.encode(encoding)
  100. return unquote_plus(byte_string).decode(encoding)
  101. def set_socket_timeout(http_response, timeout):
  102. """Set the timeout of the socket from an HTTPResponse.
  103. :param http_response: An instance of ``httplib.HTTPResponse``
  104. """
  105. http_response._fp.fp._sock.settimeout(timeout)
  106. def accepts_kwargs(func):
  107. return inspect.getargspec(func)[2]
  108. def ensure_unicode(s, encoding='utf-8', errors='strict'):
  109. if isinstance(s, six.text_type):
  110. return s
  111. return unicode(s, encoding, errors)
  112. def ensure_bytes(s, encoding='utf-8', errors='strict'):
  113. if isinstance(s, unicode):
  114. return s.encode(encoding, errors)
  115. if isinstance(s, str):
  116. return s
  117. raise ValueError("Expected str or unicode, received %s." % type(s))
  118. try:
  119. from collections import OrderedDict
  120. except ImportError:
  121. # Python2.6 we use the 3rd party back port.
  122. from ordereddict import OrderedDict
  123. if sys.version_info[:2] == (2, 6):
  124. import simplejson as json
  125. # In py26, invalid xml parsed by element tree
  126. # will raise a plain old SyntaxError instead of
  127. # a real exception, so we need to abstract this change.
  128. XMLParseError = SyntaxError
  129. # Handle https://github.com/shazow/urllib3/issues/497 for py2.6. In
  130. # python2.6, there is a known issue where sometimes we cannot read the SAN
  131. # from an SSL cert (http://bugs.python.org/issue13034). However, newer
  132. # versions of urllib3 will warn you when there is no SAN. While we could
  133. # just turn off this warning in urllib3 altogether, we _do_ want warnings
  134. # when they're legitimate warnings. This method tries to scope the warning
  135. # filter to be as specific as possible.
  136. def filter_ssl_san_warnings():
  137. warnings.filterwarnings(
  138. 'ignore',
  139. message="Certificate has no.*subjectAltName.*",
  140. category=exceptions.SecurityWarning,
  141. module=".*urllib3\.connection")
  142. else:
  143. import xml.etree.cElementTree
  144. XMLParseError = xml.etree.cElementTree.ParseError
  145. import json
  146. def filter_ssl_san_warnings():
  147. # Noop for non-py26 versions. We will parse the SAN
  148. # appropriately.
  149. pass
  150. def filter_ssl_warnings():
  151. # Ignore warnings related to SNI as it is not being used in validations.
  152. warnings.filterwarnings(
  153. 'ignore',
  154. message="A true SSLContext object is not available.*",
  155. category=exceptions.InsecurePlatformWarning,
  156. module=".*urllib3\.util\.ssl_")
  157. filter_ssl_san_warnings()
  158. @classmethod
  159. def from_dict(cls, d):
  160. new_instance = cls()
  161. for key, value in d.items():
  162. new_instance[key] = value
  163. return new_instance
  164. @classmethod
  165. def from_pairs(cls, pairs):
  166. new_instance = cls()
  167. for key, value in pairs:
  168. new_instance[key] = value
  169. return new_instance
  170. HTTPHeaders.from_dict = from_dict
  171. HTTPHeaders.from_pairs = from_pairs
  172. def copy_kwargs(kwargs):
  173. """
  174. There is a bug in Python versions < 2.6.5 that prevents you
  175. from passing unicode keyword args (#4978). This function
  176. takes a dictionary of kwargs and returns a copy. If you are
  177. using Python < 2.6.5, it also encodes the keys to avoid this bug.
  178. Oh, and version_info wasn't a namedtuple back then, either!
  179. """
  180. vi = sys.version_info
  181. if vi[0] == 2 and vi[1] <= 6 and vi[3] < 5:
  182. copy_kwargs = {}
  183. for key in kwargs:
  184. copy_kwargs[key.encode('utf-8')] = kwargs[key]
  185. else:
  186. copy_kwargs = copy.copy(kwargs)
  187. return copy_kwargs
  188. def total_seconds(delta):
  189. """
  190. Returns the total seconds in a ``datetime.timedelta``.
  191. Python 2.6 does not have ``timedelta.total_seconds()``, so we have
  192. to calculate this ourselves. On 2.7 or better, we'll take advantage of the
  193. built-in method.
  194. The math was pulled from the ``datetime`` docs
  195. (http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
  196. :param delta: The timedelta object
  197. :type delta: ``datetime.timedelta``
  198. """
  199. if sys.version_info[:2] != (2, 6):
  200. return delta.total_seconds()
  201. day_in_seconds = delta.days * 24 * 3600.0
  202. micro_in_seconds = delta.microseconds / 10.0**6
  203. return day_in_seconds + delta.seconds + micro_in_seconds
  204. # Checks to see if md5 is available on this system. A given system might not
  205. # have access to it for various reasons, such as FIPS mode being enabled.
  206. try:
  207. hashlib.md5()
  208. MD5_AVAILABLE = True
  209. except ValueError:
  210. MD5_AVAILABLE = False
  211. def get_md5(*args, **kwargs):
  212. """
  213. Attempts to get an md5 hashing object.
  214. :param raise_error_if_unavailable: raise an error if md5 is unavailable on
  215. this system. If False, None will be returned if it is unavailable.
  216. :type raise_error_if_unavailable: bool
  217. :param args: Args to pass to the MD5 constructor
  218. :param kwargs: Key word arguments to pass to the MD5 constructor
  219. :return: An MD5 hashing object if available. If it is unavailable, None
  220. is returned if raise_error_if_unavailable is set to False.
  221. """
  222. if MD5_AVAILABLE:
  223. return hashlib.md5(*args, **kwargs)
  224. else:
  225. raise MD5UnavailableError()