compat.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. try:
  23. import simplejson as json
  24. except ImportError:
  25. import json
  26. # ---------
  27. # Specifics
  28. # ---------
  29. if is_py2:
  30. from urllib import (
  31. quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
  32. proxy_bypass, proxy_bypass_environment, getproxies_environment)
  33. from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
  34. from urllib2 import parse_http_list
  35. import cookielib
  36. from Cookie import Morsel
  37. from StringIO import StringIO
  38. # Keep OrderedDict for backwards compatibility.
  39. from collections import Callable, Mapping, MutableMapping, OrderedDict
  40. builtin_str = str
  41. bytes = str
  42. str = unicode
  43. basestring = basestring
  44. numeric_types = (int, long, float)
  45. integer_types = (int, long)
  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. builtin_str = str
  56. str = str
  57. bytes = bytes
  58. basestring = (str, bytes)
  59. numeric_types = (int, float)
  60. integer_types = (int,)