compat.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """
  2. requests.compat
  3. ~~~~~~~~~~~~~~~
  4. This module previously handled import compatibility issues
  5. between Python 2 and Python 3. It remains for backwards
  6. compatibility until the next major version.
  7. """
  8. import importlib
  9. import sys
  10. # -------------------
  11. # Character Detection
  12. # -------------------
  13. def _resolve_char_detection():
  14. """Find supported character detection libraries."""
  15. chardet = None
  16. for lib in ("chardet", "charset_normalizer"):
  17. if chardet is None:
  18. try:
  19. chardet = importlib.import_module(lib)
  20. except ImportError:
  21. pass
  22. return chardet
  23. chardet = _resolve_char_detection()
  24. # -------
  25. # Pythons
  26. # -------
  27. # Syntax sugar.
  28. _ver = sys.version_info
  29. #: Python 2.x?
  30. is_py2 = _ver[0] == 2
  31. #: Python 3.x?
  32. is_py3 = _ver[0] == 3
  33. # json/simplejson module import resolution
  34. has_simplejson = False
  35. try:
  36. import simplejson as json
  37. has_simplejson = True
  38. except ImportError:
  39. import json
  40. if has_simplejson:
  41. from simplejson import JSONDecodeError
  42. else:
  43. from json import JSONDecodeError
  44. # Keep OrderedDict for backwards compatibility.
  45. from collections import OrderedDict
  46. from collections.abc import Callable, Mapping, MutableMapping
  47. from http import cookiejar as cookielib
  48. from http.cookies import Morsel
  49. from io import StringIO
  50. # --------------
  51. # Legacy Imports
  52. # --------------
  53. from urllib.parse import (
  54. quote,
  55. quote_plus,
  56. unquote,
  57. unquote_plus,
  58. urldefrag,
  59. urlencode,
  60. urljoin,
  61. urlparse,
  62. urlsplit,
  63. urlunparse,
  64. )
  65. from urllib.request import (
  66. getproxies,
  67. getproxies_environment,
  68. parse_http_list,
  69. proxy_bypass,
  70. proxy_bypass_environment,
  71. )
  72. builtin_str = str
  73. str = str
  74. bytes = bytes
  75. basestring = (str, bytes)
  76. numeric_types = (int, float)
  77. integer_types = (int,)