Exemplo n.º 1
0
def _http_call(url, method, authorization, token, **kw):
    """
    :param url: http request url
    :param method: http request method
    :param authorization: push authorization
    :param kw: params
    """
    params = _encode_params(**kw)
    http_url = '%s?%s' % (url,
                          params) if method == Constants.__HTTP_GET__ else url
    http_body = None if method == Constants.__HTTP_GET__ else params
    req = urllib2.Request(http_url, data=http_body)
    if authorization:
        req.add_header('Authorization', 'key=%s' % authorization)
    if token:
        req.add_header('X-PUSH-AUDIT-TOKEN', token)
    if Constants.auto_switch_host and ServerSwitch().need_refresh_host_list():
        req.add_header('X-PUSH-HOST-LIST', 'true')
    req.add_header('Content-Type',
                   'application/x-www-form-urlencoded;charset=UTF-8')
    try:
        resp = urllib2.urlopen(req, timeout=5)
        host_list = resp.info().getheader('X-PUSH-HOST-LIST')
        if host_list:
            ServerSwitch().initialize(host_list)
        r = _parse_json(resp.read())
        if hasattr(r, 'code'):
            if r.code != 0:
                raise APIError(r.code, r.get('description', ''),
                               r.get('reason', ''))
        return r
    except urllib2.URLError, e:
        raise APIError('-5', e.read(), 'http error')
Exemplo n.º 2
0
 def _try_http_request(self,
                       request_path,
                       retry_times,
                       method=Constants.__HTTP_POST__,
                       **kw):
     is_fail, try_time, result, sleep_time = True, 0, None, 1
     while is_fail and try_time < retry_times:
         try:
             if method == Constants.__HTTP_POST__:
                 result = self.http_post(request_path, **kw)
             elif method == Constants.__HTTP_GET__:
                 result = self.http_get(request_path, **kw)
             else:
                 raise APIError('-2',
                                'not support %s http request' % method,
                                'http error')
             is_fail = False
         except APIError as ex:
             '''
                 URLError failure retry
             '''
             if ex.error_code == '-5':
                 is_fail = True
             logging.error('code:[%s] - description:[%s] - reason:[%s]' %
                           (ex.error_code, ex.error, ex.request))
             try_time += 1
             time.sleep(sleep_time)
             if 2 * sleep_time < _MAX_BACKOFF_DELAY:
                 sleep_time *= 2
     if not result:
         raise APIError('-3', 'retry %s time failure' % retry_times,
                        'request error')
     return result
Exemplo n.º 3
0
    def __common_subscribe(self,
                           request_path,
                           subscribe_type,
                           target,
                           topic,
                           retry_times=3,
                           **option_args):
        params = dict()
        target_str = target
        if isinstance(target, list):
            target_str = __TARGET_SPLITTER__.join(target)

        if subscribe_type == Constants.subscribe_type.RegId:
            params[Constants.http_param_registration_id] = target_str
        elif subscribe_type == Constants.subscribe_type.Alias:
            params[Constants.http_param_alias] = target_str
        else:
            raise APIError(-1, 'subscribe type %s error' % subscribe_type,
                           'args error')

        params[Constants.http_param_topic] = topic
        for option_name in option_args:
            params[option_name] = option_args[option_name]

        return self._try_http_request(request_path, retry_times, **params)
Exemplo n.º 4
0
 def multi_broadcast(self, push_message, topics, broadcast_topic_op, retry_times=3):
     """
     发送多topic消息(multi)
     :param push_message: 消息体(请求参数对象)
     :param topics: topic集合(list)
     :param broadcast_topic_op: topic类型[交集, 并集, 差集]
     :param retry_times: 重试次数
     """
     if isinstance(topics, list):
         if len(topics) > _BROADCAST_TOPIC_MAX:
             raise APIError(-1, 'topics more than max topic 5', 'args limit')
         push_message[Constants.http_param_topics] = _TOPIC_SPLITTER.join(topics)
         push_message[Constants.http_param_topic_op] = broadcast_topic_op
         return self._try_http_request(Constants.request_path.V3_MILTI_TOPIC_BROADCAST, retry_times,
                                       **push_message)
     else:
         raise APIError(-1, 'topic must be list', 'args illegal')
Exemplo n.º 5
0
                          method=Constants.__HTTP_POST__,
                          **kw):
        is_fail, try_time, result, sleep_time = True, 0, None, 1
        while is_fail and try_time < retry_times:
            try:
                if method == Constants.__HTTP_POST__:
                    result = self.http_post(request_path, **kw)
                elif method == Constants.__HTTP_GET__:
                    result = self.http_get(request_path, **kw)
                else:
                    raise APIError('-2',
                                   'not support %s http request' % method,
                                   'http error')
                is_fail = False
            except APIError, ex:
                '''
                    URLError failure retry
                '''
                if ex.error_code == '-5':
                    is_fail = True
                logging.error('code:[%s] - description:[%s] - reason:[%s]' %
                              (ex.error_code, ex.error, ex.request))
                try_time += 1
                time.sleep(sleep_time)
                if 2 * sleep_time < _MAX_BACKOFF_DELAY:
                    sleep_time *= 2
        if not result:
            raise APIError('-3', 'retry %s time failure' % retry_times,
                           'request error')
        return result