compat.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # coding: utf-8
  2. import base64
  3. __all__ = [
  4. 'urlparse', 'string_types',
  5. 'COMPACT_SEPARATORS', 'VERBOSE_SEPARATORS'
  6. ]
  7. try:
  8. # Python 2
  9. import urlparse
  10. import cookielib as cookiejar
  11. string_types = (basestring,)
  12. text_type = unicode
  13. COMPACT_SEPARATORS = (b',', b':')
  14. VERBOSE_SEPARATORS = (b',', b': ')
  15. def b64encode(input_string):
  16. # Provide a consistently-as-unicode interface across 2.x and 3.x
  17. return base64.b64encode(input_string)
  18. except ImportError:
  19. # Python 3
  20. import urllib.parse as urlparse
  21. from io import IOBase
  22. from http import cookiejar
  23. string_types = (str,)
  24. text_type = str
  25. COMPACT_SEPARATORS = (',', ':')
  26. VERBOSE_SEPARATORS = (',', ': ')
  27. def b64encode(input_string):
  28. # Provide a consistently-as-unicode interface across 2.x and 3.x
  29. return base64.b64encode(input_string.encode('ascii')).decode('ascii')
  30. def force_bytes(string):
  31. if isinstance(string, string_types):
  32. return string.encode('utf-8')
  33. return string
  34. def force_text(string):
  35. if not isinstance(string, string_types):
  36. return string.decode('utf-8')
  37. return string
  38. try:
  39. import click
  40. console_style = click.style
  41. except ImportError:
  42. def console_style(text, **kwargs):
  43. return text
  44. try:
  45. from tempfile import _TemporaryFileWrapper
  46. except ImportError:
  47. _TemporaryFileWrapper = None