当前位置: 首页>>代码示例>>Python>>正文


Python errors.HttpError方法代码示例

本文整理汇总了Python中apiclient.errors.HttpError方法的典型用法代码示例。如果您正苦于以下问题:Python errors.HttpError方法的具体用法?Python errors.HttpError怎么用?Python errors.HttpError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在apiclient.errors的用法示例。


在下文中一共展示了errors.HttpError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: watchChange

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def watchChange(drive, channel_id, channel_type, channel_address,
              channel_token=None, expiration=None):
    # Watch for all changes to a user's Drive.
    # Args:
    # service: Drive API service instance.
    # channel_id: Unique string that identifies this channel.
    # channel_type: Type of delivery mechanism used for this channel.
    # channel_address: Address where notifications are delivered.
    # channel_token: An arbitrary string delivered to the target address with
    #               each notification delivered over this channel. Optional.
    # channel_address: Address where notifications are delivered. Optional.
    # Returns:
    # The created channel if successful
    # Raises:
    # apiclient.errors.HttpError: if http request to create channel fails.
    body = {
        'id': channel_id,
        'type': channel_type,
        'address': channel_address
    }
    if channel_token:
        body['token'] = channel_token
    if expiration:
        body['expiration'] = expiration
    return drive.auth.service.changes().watch(body=body).execute() 
开发者ID:janeczku,项目名称:calibre-web,代码行数:27,代码来源:gdriveutils.py

示例2: getChangeById

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def getChangeById (drive, change_id):
    # Print a single Change resource information.
    #
    # Args:
    # service: Drive API service instance.
    # change_id: ID of the Change resource to retrieve.
    try:
        change = drive.auth.service.changes().get(changeId=change_id).execute()
        return change
    except (errors.HttpError) as error:
        log.error(error)
        return None
    except Exception as e:
        log.error(e)
        return None


# Deletes the local hashes database to force search for new folder names 
开发者ID:janeczku,项目名称:calibre-web,代码行数:20,代码来源:gdriveutils.py

示例3: __create_dataset_if_missing

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def __create_dataset_if_missing(self, project_id, dataset_id, location):
        logging.info("Creating dataset %s:%s in %s location",
                     project_id, dataset_id, location)
        body = {
            'datasetReference': {
                'projectId': project_id,
                'datasetId': dataset_id
            },
            'location': location
        }
        try:
            self.service.datasets().insert(
                projectId=project_id, body=body
            ).execute()
        except HttpError as e:
            if e.resp.status == 409:
                logging.info("Dataset %s:%s already exists", project_id,
                             dataset_id)
            else:
                raise e 
开发者ID:ocadotechnology,项目名称:gcp-census,代码行数:22,代码来源:model_creator.py

示例4: test_should_propagate_dataset_500_error

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def test_should_propagate_dataset_500_error(self, _create_http):
        # given
        http_mock = Mock(wraps=HttpMockSequence([
            ({'status': '200'}, test_utils.content(
                'tests/json_samples/bigquery_v2_test_schema.json')),
            ({'status': '500'}, '')
        ]))
        _create_http.return_value = http_mock
        model_provider = Mock()
        model_provider.list_groups.return_value = ["missing_dataset1"]

        under_test = ModelCreator(model_provider)

        # when
        with self.assertRaises(HttpError) as context:
            under_test.create_missing_datasets()

        # then
        calls = http_mock.mock_calls
        self.assertEqual(2, len(calls))
        self.assertEqual(500, context.exception.resp.status) 
开发者ID:ocadotechnology,项目名称:gcp-census,代码行数:23,代码来源:model_creator_test.py

示例5: test_should_propagate_table_500_error

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def test_should_propagate_table_500_error(self, _create_http):
        # given
        http_mock = Mock(wraps=HttpMockSequence([
            ({'status': '200'}, test_utils.content(
                'tests/json_samples/bigquery_v2_test_schema.json')),
            ({'status': '500'}, '')
        ]))
        _create_http.return_value = http_mock
        model_provider = Mock()
        model_provider.list_tables.return_value = [Table("group", "name1", {})]

        under_test = ModelCreator(model_provider)

        # when
        with self.assertRaises(HttpError) as context:
            under_test.create_missing_tables()

        # then
        calls = http_mock.mock_calls
        self.assertEqual(2, len(calls))
        self.assertEqual(500, context.exception.resp.status) 
开发者ID:ocadotechnology,项目名称:gcp-census,代码行数:23,代码来源:model_creator_test.py

示例6: autoretry

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def autoretry(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        global _fail_count
        while True:
            try:
                r = func(*args, **kwargs)
                _fail_count = 0
                return r
            except HttpError as e:
                if not (hasattr(e, 'resp') and 'status' in e.resp
                        and e.resp['status'].isdigit and int(e.resp['status']) >= 500):
                    raise  # we do not want to retry auth errors etc.
                _fail_count += 1
                wait_for = min(2 ** (_fail_count - 1) * 15 * 60 * (1 + random.random()), 24 * 60 * 60)
                log.exception('Call Failed for %s time(s). Retrying in %s seconds: %s',
                              _fail_count, wait_for, str(e))
                time.sleep(wait_for)
            except socket.error:
                transient_error_wait = 2
                log.exception('Socket error, retrying in {} seconds.'.format(transient_error_wait))
                time.sleep(transient_error_wait)
    return wrapper 
开发者ID:afilipovich,项目名称:gglsbl,代码行数:25,代码来源:protocol.py

示例7: GetUserAttributes

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def GetUserAttributes(self, user_email):
    """Helper to retrieve user attributes from the Admin SDK API.

    Args:
      user_email: String email address of the form user@domain.com.

    Returns:
      Dictionary of user_attributes discovered.

    Raises:
      MessageRecallError: If unable to execute the API call.
    """
    request = self._users_collection.get(userKey=user_email)
    try:
      return request.execute(
          http=credentials_utils.GetAuthorizedHttp(user_email))
    except (HttpError, httplib.HTTPException) as e:
      if e.resp.status == 403:  # If user is not an admin...
        return {}
      raise 
开发者ID:google,项目名称:googleapps-message-recall,代码行数:22,代码来源:user_retriever.py

示例8: get_subscription

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def get_subscription(self, deadline=60):
        sub = None
        log.debug("getting subscription")
        try:
            # note: subscriptions are a flat namespace in a project
            # we delete then recreate the subscription if it exists
            # so we don't execute old messages

            self.client.projects().subscriptions().delete(
                subscription='projects/{}/subscriptions/{}'.format(
                    self.project, self.subname)).execute()
            log.debug("deleted existing subscription")
        except HttpError as e:
            if e.resp.status == 404:
                sub = self.create_subscription(deadline=deadline)
            else:
                raise
        else:
            sub = self.create_subscription(deadline=deadline)
        log.debug("subscription %s" % sub)
        return sub 
开发者ID:GoogleCloudPlatform,项目名称:reliable-task-scheduling-compute-engine-sample,代码行数:23,代码来源:cron_executor.py

示例9: _setup_subscription

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def _setup_subscription(self):
        """Creates a subscription if it does not exist."""
        subscription_name = pubsub_utils.get_full_subscription_name()
        try:
            self.client.projects().subscriptions().get(
                subscription=subscription_name).execute()
        except errors.HttpError as e:
            if e.resp.status == 404:
                body = {
                    'topic': pubsub_utils.get_full_topic_name(),
                    'pushConfig': {
                        'pushEndpoint': pubsub_utils.get_app_endpoint_url()
                    }
                }
                self.client.projects().subscriptions().create(
                    name=subscription_name, body=body).execute()
            else:
                logging.exception(e)
                raise 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-python,代码行数:21,代码来源:main.py

示例10: get_word_count

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def get_word_count(vision, image_bytes):
  """Use Vision API to detect the count of words in the image."""
  vision_req_body = {
      'requests': [{
          'image': {
              'content': image_bytes,
          },
          'features': [{
              'type': 'TEXT_DETECTION'
          }]
      }]
  }
  try:
    result = run_deid_lib.request_with_retry(
        vision.annotate(body=vision_req_body).execute)
  except errors.HttpError as error:
    raise error
  if 'error' in result:
    raise Exception('Annotate() failed: {}'.format(result['error']))

  if result and result['responses'] and result['responses'][0]:
    return result['responses'][0]['fullTextAnnotation']['text'].count('\n')
  else:
    return 0 
开发者ID:GoogleCloudPlatform,项目名称:healthcare-deid,代码行数:26,代码来源:inspect_dicom.py

示例11: execute_request

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def execute_request(request, timeout=TIMEOUT_DEFAULT):
    """Execute Google API request
    Automatic retry upon Google backend error (500) until timeout
    """
    while timeout >= 0:
        try:
            response = request.execute()
        except HttpError as e:
            if int(e.args[0]['status']) == 500:
                timeout -= RETRY_INTERVAL
                time.sleep(RETRY_INTERVAL)
                continue
            raise e
        else:
            return response
    raise TimeoutError 
开发者ID:cfbao,项目名称:google-drive-trash-cleaner,代码行数:18,代码来源:cleaner.py

示例12: call_back

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def call_back(self, request_id, response, exception):
    """The global call_back method for the BatchQueue instance.

    Called when the API responds.
    It keeps track of the number of times the response is called, and if
    the full quota is freed up, it will call execute.

    Args:
      request_id: The request id.
      response: The deserialized response object.
      exception: The apiclient.errors.HttpError exception object if an HTTP
        error occurred while processing the request, or None if no
        error occurred.
    """
    self.count += 1
    if self.count == self.quota:
      self.count = 0
      self.execute()

    callback = self.call_backs[request_id]
    callback(request_id, response, exception) 
开发者ID:googleanalytics,项目名称:api-samples,代码行数:23,代码来源:batchqueue.py

示例13: add

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def add(self, request, callback, request_id=None):
    """Adds the request to the queue.

    Args:
      request: HttpRequest, Request to add to the batch.
      callback: callable, A callback to be called for this response, of the
        form callback(id, response, exception). The first parameter is the
        request id, and the second is the deserialized response object. The
        third is an apiclient.errors.HttpError exception object if an HTTP error
        occurred while processing the request, or None if no errors occurred.
      request_id: string, A unique id for the request. The id will be passed to
        the callback with the response.
    """

    # Create a unique id if one does not exist.
    if not request_id:
      request_id = str(uuid.uuid4())

    # Add the callback to the dictionary of call backs.
    self.call_backs[request_id] = callback

    # Add the request to the queue.
    self.queue.put((request, request_id)) 
开发者ID:googleanalytics,项目名称:api-samples,代码行数:25,代码来源:batchqueue.py

示例14: retry

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def retry(self, func, max_retries=DEFAULT_MAX_RETRIES):
    """Decorator implementing retries with exponentially increasing delays."""
    @wraps(func)
    def func_with_retries(*args, **kwargs):
      """Retriable version of function being decorated."""
      tries = 0
      while tries < max_retries:
        try:
          return func(*args, **kwargs)
        except HttpError as e:
          # If it is a client side error, then there's no reason to retry.
          if e.resp.status > 399 and e.resp.status < 500:
            raise e
        except HTTPError as e:
          # If it is a client side error, then there's no reason to retry.
          if e.code > 399 and e.code < 500:
            raise e
        except Exception as e:  # pylint: disable=broad-except
          tries += 1
          delay = 5 * 2 ** (tries + random())
          time.sleep(delay)
      return func(*args, **kwargs)
    return func_with_retries 
开发者ID:google,项目名称:crmint,代码行数:25,代码来源:workers.py

示例15: _real_upload_video

# 需要导入模块: from apiclient import errors [as 别名]
# 或者: from apiclient.errors import HttpError [as 别名]
def _real_upload_video(self, insert_request):
        response = None
        error = None
        retry = 0
        print('File upload in progress...', end='')
        while response is None:
            try:
                status, response = insert_request.next_chunk()
                print('.', end='')
                if 'id' in response:
                    print()
                    return response['id']
            except HttpError as err:
                if err.resp.status in RETRIABLE_STATUS_CODES:
                    error = True
                else:
                    raise
            except RETRIABLE_EXCEPTIONS:
                error = True

            if error:
                retry += 1
                if retry > MAX_RETRIES:
                    raise Exception('Maximum retry are fail')

                sleep_seconds = random.random() * 2 ** retry
                time.sleep(sleep_seconds) 
开发者ID:Welltory,项目名称:Zoom2Youtube,代码行数:29,代码来源:youtube.py


注:本文中的apiclient.errors.HttpError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。