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.

compat.py 2.2KB

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- coding: utf-8 -*-
  2. """
  3. 兼容Python版本
  4. """
  5. import sys
  6. is_py2 = (sys.version_info[0] == 2)
  7. is_py3 = (sys.version_info[0] == 3)
  8. is_py33 = (sys.version_info[0] == 3 and sys.version_info[1] == 3)
  9. try:
  10. import simplejson as json
  11. except (ImportError, SyntaxError):
  12. import json
  13. if is_py2:
  14. from urllib import quote as urlquote, unquote as urlunquote
  15. from urlparse import urlparse, parse_qs, urlsplit
  16. def to_bytes(data):
  17. """若输入为unicode, 则转为utf-8编码的bytes;其他则原样返回。"""
  18. if isinstance(data, unicode):
  19. return data.encode('utf-8')
  20. else:
  21. return data
  22. def to_string(data):
  23. """把输入转换为str对象"""
  24. return to_bytes(data)
  25. def to_unicode(data):
  26. """把输入转换为unicode,要求输入是unicode或者utf-8编码的bytes。"""
  27. if isinstance(data, bytes):
  28. return data.decode('utf-8')
  29. else:
  30. return data
  31. def stringify(input):
  32. if isinstance(input, dict):
  33. return dict([(stringify(key), stringify(value)) for key,value in input.iteritems()])
  34. elif isinstance(input, list):
  35. return [stringify(element) for element in input]
  36. elif isinstance(input, unicode):
  37. return input.encode('utf-8')
  38. else:
  39. return input
  40. builtin_str = str
  41. bytes = str
  42. str = unicode
  43. elif is_py3:
  44. from urllib.parse import quote as urlquote, unquote as urlunquote
  45. from urllib.parse import urlparse, parse_qs, urlsplit
  46. def to_bytes(data):
  47. """若输入为str(即unicode),则转为utf-8编码的bytes;其他则原样返回"""
  48. if isinstance(data, str):
  49. return data.encode(encoding='utf-8')
  50. else:
  51. return data
  52. def to_string(data):
  53. """若输入为bytes,则认为是utf-8编码,并返回str"""
  54. if isinstance(data, bytes):
  55. return data.decode('utf-8')
  56. else:
  57. return data
  58. def to_unicode(data):
  59. """把输入转换为unicode,要求输入是unicode或者utf-8编码的bytes。"""
  60. return to_string(data)
  61. def stringify(input):
  62. return input
  63. builtin_str = str
  64. bytes = bytes
  65. str = str