You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 line
1.5KB

  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2014 Rackspace
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. # implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Compatibility module for Python 2 and 3 support."""
  16. import sys
  17. try:
  18. from urllib.parse import quote as urlquote
  19. except ImportError: # Python 2.x
  20. from urllib import quote as urlquote
  21. try:
  22. from urllib.parse import urlencode
  23. except ImportError: # Python 2.x
  24. from urllib import urlencode
  25. __all__ = (
  26. 'to_bytes',
  27. 'to_str',
  28. 'urlquote',
  29. 'urlencode',
  30. )
  31. PY3 = (3, 0) <= sys.version_info < (4, 0)
  32. PY2 = (2, 6) <= sys.version_info < (2, 8)
  33. if PY3:
  34. unicode = str # Python 3.x
  35. def to_str(b, encoding='utf-8'):
  36. """Ensure that b is text in the specified encoding."""
  37. if hasattr(b, 'decode') and not isinstance(b, unicode):
  38. b = b.decode(encoding)
  39. return b
  40. def to_bytes(s, encoding='utf-8'):
  41. """Ensure that s is converted to bytes from the encoding."""
  42. if hasattr(s, 'encode') and not isinstance(s, bytes):
  43. s = s.encode(encoding)
  44. return s