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.

68 satır
2.3KB

  1. #coding=utf8
  2. TRANSLATE = 'Chinese'
  3. class ReturnValue(dict):
  4. ''' turn return value of itchat into a boolean value
  5. for requests:
  6. ..code::python
  7. import requests
  8. r = requests.get('http://httpbin.org/get')
  9. print(ReturnValue(rawResponse=r)
  10. for normal dict:
  11. ..code::python
  12. returnDict = {
  13. 'BaseResponse': {
  14. 'Ret': 0,
  15. 'ErrMsg': 'My error msg', }, }
  16. print(ReturnValue(returnDict))
  17. '''
  18. def __init__(self, returnValueDict={}, rawResponse=None):
  19. if rawResponse:
  20. try:
  21. returnValueDict = rawResponse.json()
  22. except ValueError:
  23. returnValueDict = {
  24. 'BaseResponse': {
  25. 'Ret': -1004,
  26. 'ErrMsg': 'Unexpected return value', },
  27. 'Data': rawResponse.content, }
  28. for k, v in returnValueDict.items():
  29. self[k] = v
  30. if not 'BaseResponse' in self:
  31. self['BaseResponse'] = {
  32. 'ErrMsg': 'no BaseResponse in raw response',
  33. 'Ret': -1000, }
  34. if TRANSLATE:
  35. self['BaseResponse']['RawMsg'] = self['BaseResponse'].get('ErrMsg', '')
  36. self['BaseResponse']['ErrMsg'] = \
  37. TRANSLATION[TRANSLATE].get(
  38. self['BaseResponse'].get('Ret', '')) \
  39. or self['BaseResponse'].get('ErrMsg', u'No ErrMsg')
  40. self['BaseResponse']['RawMsg'] = \
  41. self['BaseResponse']['RawMsg'] or self['BaseResponse']['ErrMsg']
  42. def __nonzero__(self):
  43. return self['BaseResponse'].get('Ret') == 0
  44. def __bool__(self):
  45. return self.__nonzero__()
  46. def __str__(self):
  47. return '{%s}' % ', '.join(
  48. ['%s: %s' % (repr(k),repr(v)) for k,v in self.items()])
  49. def __repr__(self):
  50. return '<ItchatReturnValue: %s>' % self.__str__()
  51. TRANSLATION = {
  52. 'Chinese': {
  53. -1000: u'返回值不带BaseResponse',
  54. -1001: u'无法找到对应的成员',
  55. -1002: u'文件位置错误',
  56. -1003: u'服务器拒绝连接',
  57. -1004: u'服务器返回异常值',
  58. -1005: u'参数错误',
  59. -1006: u'无效操作',
  60. 0: u'请求成功',
  61. },
  62. }