compat.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.compat
  4. ~~~~~~~~~~~~~~~
  5. This module handles import compatibility issues between Python 2 and
  6. Python 3.
  7. """
  8. try:
  9. import chardet
  10. except ImportError:
  11. import charset_normalizer as chardet
  12. import sys
  13. # -------
  14. # Pythons
  15. # -------
  16. # Syntax sugar.
  17. _ver = sys.version_info
  18. #: Python 2.x?
  19. is_py2 = (_ver[0] == 2)
  20. #: Python 3.x?
  21. is_py3 = (_ver[0] == 3)
  22. has_simplejson = False
  23. try:
  24. import simplejson as json
  25. has_simplejson = True
  26. except ImportError:
  27. import json
  28. # ---------
  29. # Specifics
  30. # ---------
  31. if is_py2:
  32. from urllib import (
  33. quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
  34. proxy_bypass, proxy_bypass_environment, getproxies_environment)
  35. from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
  36. from urllib2 import parse_http_list
  37. import cookielib
  38. from Cookie import Morsel
  39. from StringIO import StringIO
  40. # Keep OrderedDict for backwards compatibility.
  41. from collections import Callable, Mapping, MutableMapping, OrderedDict
  42. builtin_str = str
  43. bytes = str
  44. str = unicode
  45. basestring = basestring
  46. numeric_types = (int, long, float)
  47. integer_types = (int, long)
  48. JSONDecodeError = ValueError
  49. elif is_py3:
  50. from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
  51. from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment
  52. from http import cookiejar as cookielib
  53. from http.cookies import Morsel
  54. from io import StringIO
  55. # Keep OrderedDict for backwards compatibility.
  56. from collections import OrderedDict
  57. from collections.abc import Callable, Mapping, MutableMapping
  58. if has_simplejson:
  59. from simplejson import JSONDecodeError
  60. else:
  61. from json import JSONDecodeError
  62. builtin_str = str
  63. str = str
  64. bytes = bytes
  65. basestring = (str, bytes)
  66. numeric_types = (int, float)
  67. integer_types = (int,)