compat.py 2.0 KB

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