util.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright 2014 Baidu, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. """
  12. This module provides some python2 and python3's compatible functions for BTS.
  13. """
  14. import sys
  15. import logging
  16. from baidubce.exception import BceClientError
  17. from baidubce.services.bts import PYTHON_VERSION_ERROR
  18. PY2 = sys.version_info[0] == 2
  19. PY3 = sys.version_info[0] == 3
  20. if PY3:
  21. import urllib.parse
  22. else:
  23. import urllib
  24. _logger = logging.getLogger(__name__)
  25. def _encode(s):
  26. """
  27. _encode
  28. :param s: s
  29. :type s: string
  30. :return:
  31. :rtype string
  32. """
  33. if PY2:
  34. return urllib.quote(s)
  35. if PY3:
  36. return urllib.parse.quote(s)
  37. ex = BceClientError(PYTHON_VERSION_ERROR)
  38. _logger.debug(ex)
  39. raise ex
  40. def _decode(s):
  41. """
  42. _decode
  43. :param s: s
  44. :type s: string
  45. :return:
  46. :rtype string
  47. """
  48. if PY2:
  49. return urllib.unquote(s)
  50. if PY3:
  51. return urllib.parse.unquote(s)
  52. ex = BceClientError(PYTHON_VERSION_ERROR)
  53. _logger.debug(ex)
  54. raise ex