APISenderBase.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import logging
  2. import time
  3. import json
  4. import urllib.request, urllib.parse, urllib.error
  5. import urllib.request, urllib.error, urllib.parse
  6. from Service.VivoPushService.push_admin.APIConstants import Constants
  7. from Service.VivoPushService.push_admin.APIError import APIError
  8. _MAX_BACKOFF_DELAY = 1024000
  9. class JsonDict(dict):
  10. def __getattr__(self, item):
  11. try:
  12. return self[item]
  13. except KeyError:
  14. raise AttributeError(r"'JsonDict' object has no attribute %s'" % item)
  15. def __setattr__(self, key, value):
  16. self[key] = value
  17. def _parse_json(body):
  18. """
  19. convert json object to python object
  20. :param body: response data
  21. """
  22. def _obj_hook(pairs):
  23. o = JsonDict()
  24. for k, v in pairs.items():
  25. o[str(k)] = v
  26. return o
  27. return json.loads(body, object_hook=_obj_hook)
  28. def _build_request_url(request_path):
  29. return Constants.http_server + request_path[0]
  30. def _http_call(url, method, token, **message):
  31. """
  32. :param url: http request url
  33. :param method: http request method
  34. :param message: params
  35. """
  36. params = _encode_params(message) if method == Constants.__HTTP_GET__ else ''
  37. http_url = '%s?%s' % (url, params) if method == Constants.__HTTP_GET__ else url
  38. http_body = None if method == Constants.__HTTP_GET__ else message
  39. req = urllib.request.Request(http_url, data=json.dumps(http_body).encode("utf-8"))
  40. if token:
  41. req.add_header('authToken', token)
  42. req.add_header('Content-Type', 'application/json;charset=UTF-8')
  43. try:
  44. resp = urllib.request.urlopen(req, timeout=5)
  45. r = _parse_json(resp.read().decode())
  46. return r
  47. except urllib.error.HTTPError as e:
  48. # 处理HTTPError,访问代码
  49. raise APIError('-5', e.reason, 'http error ' + str(e.code))
  50. except urllib.error.URLError as e:
  51. # 处理URLError,因为URLError没有code属性
  52. raise APIError('-5', e.reason, 'http error: ' + e.reason)
  53. except BaseException as e:
  54. raise e
  55. def _encode_params(kw):
  56. """
  57. splic get request url
  58. :param kw: params
  59. """
  60. args = ''
  61. s = ''
  62. for k, v in kw.items():
  63. for t in v:
  64. s = s+ str(t) + ','
  65. args = '%s=%s' %(k, s[:-1])
  66. return args
  67. class Base(object):
  68. def __init__(self, secret, token=None):
  69. self.secret = secret
  70. self.token = token
  71. def set_token(self, token):
  72. self.token = token
  73. def _http_request(self, request_path, method, **message):
  74. """
  75. :param request_path: http interface
  76. :param method: GET|POST
  77. :param message: params
  78. """
  79. request_url = _build_request_url(request_path)
  80. try:
  81. ret = _http_call(request_url, method, self.token, **message)
  82. return ret
  83. except APIError as ex:
  84. logging.error("%s request: [%s] error [%s]" % (Constants.http_server, request_url, ex))
  85. raise ex
  86. def http_post(self, request_path, **message):
  87. logging.info("POST %s" % request_path[0])
  88. return self._http_request(request_path, Constants.__HTTP_POST__, **message)
  89. def http_get(self, request_path, **message):
  90. logging.info("GET %s" % request_path[0])
  91. return self._http_request(request_path, Constants.__HTTP_GET__, **message)
  92. def _try_http_request(self, request_path, retry_times, method=Constants.__HTTP_POST__, **message):
  93. is_fail, try_time, result, sleep_time = True, 0, None, 1
  94. while is_fail and try_time < retry_times:
  95. try:
  96. if method == Constants.__HTTP_POST__:
  97. result = self.http_post(request_path, **message)
  98. elif method == Constants.__HTTP_GET__:
  99. result = self.http_get(request_path, **message)
  100. else:
  101. raise APIError('-2', 'not support %s http request' % method, 'http error')
  102. is_fail = False
  103. except APIError as ex:
  104. '''
  105. failure retry
  106. '''
  107. if ex.error_code == '-5':
  108. is_fail = True
  109. try_time += 1
  110. logging.error('code:[%s] - description:[%s] - reason:[%s] - try_time:[%s]' % (ex.error_code, ex.error, ex.request, try_time))
  111. time.sleep(sleep_time)
  112. if 2 * sleep_time < _MAX_BACKOFF_DELAY:
  113. sleep_time *= 2
  114. if not result:
  115. raise APIError('-3', 'retry %s time failure' % retry_times, 'request error')
  116. return result