Python googleapiclient.errors.HttpError() Examples

The following are 30 code examples of googleapiclient.errors.HttpError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module googleapiclient.errors , or try the search function .
Example #1
Source File: sheets_logger.py    From imgcomp-cvpr with GNU General Public License v3.0 7 votes vote down vote up
def check_connection(flags=None):
    """ Checks if link to google sheet is correctly set up. """
    try:
        credentials = _get_credentials(flags)
        http = credentials.authorize(httplib2.Http())
        discovery_url = 'https://sheets.googleapis.com/$discovery/rest?version=v4'
        service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discovery_url)

        title_cell = 'B2'
        title_cell_expected_content = 'Logs'

        result = service.spreadsheets().values().get(
            spreadsheetId=_get_spreadsheet_id(), range=title_cell).execute()
        values = result.get('values')
        if not values:
            raise GoogleSheetsAccessFailedException('No values found')
        if values[0][0] != title_cell_expected_content:
            raise GoogleSheetsAccessFailedException('Unexpected content found: {}'.format(values))
        print('Google Sheets connection established')
        return service
    except HttpError as e:
        raise GoogleSheetsAccessFailedException('HttpError: {}'.format(e)) 
Example #2
Source File: gdrive.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def watch_gdrive():
    if not config.config_google_drive_watch_changes_response:
        with open(gdriveutils.CLIENT_SECRETS, 'r') as settings:
            filedata = json.load(settings)
        if filedata['web']['redirect_uris'][0].endswith('/'):
            filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-((len('/gdrive/callback')+1))]
        else:
            filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-(len('/gdrive/callback'))]
        address = '%s/gdrive/watch/callback' % filedata['web']['redirect_uris'][0]
        notification_id = str(uuid4())
        try:
            result = gdriveutils.watchChange(gdriveutils.Gdrive.Instance().drive, notification_id,
                               'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000)
            config.config_google_drive_watch_changes_response = json.dumps(result)
            # after save(), config_google_drive_watch_changes_response will be a json object, not string
            config.save()
        except HttpError as e:
            reason=json.loads(e.content)['error']['errors'][0]
            if reason['reason'] == u'push.webhookUrlUnauthorized':
                flash(_(u'Callback domain is not verified, please follow steps to verify domain in google developer console'), category="error")
            else:
                flash(reason['message'], category="error")

    return redirect(url_for('admin.configuration')) 
Example #3
Source File: storage.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def create_bucket(self, name, object_lifecycle, cors):
    """Create a new bucket."""
    project_id = utils.get_application_id()
    request_body = {'name': name}
    if object_lifecycle:
      request_body['lifecycle'] = object_lifecycle

    if cors:
      request_body['cors'] = cors

    client = create_discovery_storage_client()
    try:
      client.buckets().insert(project=project_id, body=request_body).execute()
    except HttpError as e:
      logs.log_warn('Failed to create bucket %s: %s' % (name, e))
      raise

    return True 
Example #4
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _gadmin_member_insert(message, service, group, emails):
    """
    指定したメンバーを指定したグループに追加する

    :param service: Google API との接続
    :param group: グループのメールアドレス
    :param mail: 追加/削除するメンバーのメールアドレス
    """

    for email in emails:
        body = {
            'email': email,
        }
        try:
            service.members().insert(groupKey=group, body=body).execute()
            botsend(message, '`{}` グループに `{}` を追加しました'.format(group, email))
        except HttpError as e:
            # TODO: グループが間違っている場合とメンバーのエラーの場合わけ
            botsend(message, 'メンバーの追加に失敗しました\n`{}`'.format(e)) 
Example #5
Source File: gce.py    From iris with MIT License 6 votes vote down vote up
def get_instance(self, project_id, zone, name):
        """
       get an instance
        Args:
            zone: zone
            project_id: project id
            name: instance name
        Returns:
        """

        try:
            result = self.compute.instances().get(
                project=project_id, zone=zone,
                instance=name).execute()
        except errors.HttpError as e:
            logging.error(e)
            return None
        return result 
Example #6
Source File: gcesnaphots.py    From iris with MIT License 6 votes vote down vote up
def get_snapshot(self, project_id, name):
        """
       get an instance
        Args:
            project_id: project id
            name: instance name
        Returns:
        """

        try:
            result = self.compute.snapshots().get(
                project=project_id,
                snapshot=name).execute()
        except errors.HttpError as e:
            logging.error(e)
            return None
        return result 
Example #7
Source File: gcedisks.py    From iris with MIT License 6 votes vote down vote up
def get_disk(self, project_id, zone, name):
        """
       get an instance
        Args:
            zone: zone
            project_id: project id
            name: instance name
        Returns:
        """
        try:
            result = self.compute.disks().get(
                project=project_id, zone=zone,
                disk=name).execute()
        except errors.HttpError as e:
            logging.error(e)
            return None
        return result 
Example #8
Source File: gcs.py    From iris with MIT License 6 votes vote down vote up
def do_tag(self, project_id):

        page_token = None
        more_results = True
        while more_results:
            try:
                response = self.storage.buckets().list(
                    project=project_id, pageToken=page_token).execute()
            except errors.HttpError as e:
                logging.error(e)
                return
            if 'items' in response:
                for bucket in response['items']:
                    self.tag_one(bucket, project_id)
            if 'nextPageToken' in response:
                page_token = response['nextPageToken']
            else:
                more_results = False
        if self.counter > 0:
            self.do_batch() 
Example #9
Source File: pubsub.py    From iris with MIT License 6 votes vote down vote up
def pull(client, sub, endpoint):
    """Register a listener endpoint."""
    subscription = get_full_subscription_name(utils.get_project_id(), sub)
    body = {'pushConfig': {'pushEndpoint': endpoint}}

    @backoff.on_exception(
        backoff.expo, HttpError, max_tries=3, giveup=utils.fatal_code)
    def _do_request():
        client.projects().subscriptions().modifyPushConfig(
            subscription=subscription, body=body).execute()

    try:
        _do_request()
    except HttpError as e:

        logging.error(e)
        return 'Error', 500
    return 'ok, 204' 
Example #10
Source File: storage.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def set_acl(cloud_storage_file_path, entity, role='READER'):
  """Set the access control for a file."""
  client = create_discovery_storage_client()
  bucket, path = get_bucket_name_and_path(cloud_storage_file_path)

  try:
    return client.objectAccessControls().insert(
        bucket=bucket, object=path, body={
            'entity': entity,
            'role': role
        }).execute()
  except HttpError as e:
    if e.resp.status == 404:
      return None

    raise 
Example #11
Source File: actions_lib.py    From incubator-dlab with Apache License 2.0 6 votes vote down vote up
def remove_disk(self, instance_name, zone):
        try:
            request = self.service.disks().delete(project=self.project, zone=zone, disk=instance_name + '-secondary')
            try:
                result = request.execute()
                meta_lib.GCPMeta().wait_for_operation(result['name'], zone=zone)
                print('Disk {}-secondary removed.'.format(instance_name))
            except errors.HttpError as err:
                if err.resp.status == 404:
                    print('Disk {}-secondary was not found. Skipped'.format(instance_name))
                    return request
                else:
                    raise err
            return request
        except Exception as err:
            logging.info(
                "Unable to remove disk: " + str(err) + "\n Traceback: " + traceback.print_exc(file=sys.stdout))
            append_result(str({"error": "Unable to remove disk",
                               "error_message": str(err) + "\n Traceback: " + traceback.print_exc(
                                   file=sys.stdout)}))
            traceback.print_exc(file=sys.stdout) 
Example #12
Source File: bigtable.py    From iris with MIT License 6 votes vote down vote up
def do_tag(self, project_id):
        page_token = None
        more_results = True
        while more_results:
            try:
                result = self.bigtable.projects().instances().list(
                    parent="projects/" + project_id,
                    pageToken=page_token).execute()
            except errors.HttpError as e:
                logging.error(e)
                return
            if 'instances' in result:
                for inst in result['instances']:
                    self.tag_one(inst, project_id)
            if 'nextPageToken' in result:
                page_token = result['nextPageToken']
            else:
                more_results = False
            if self.counter > 0:
                self.do_batch() 
Example #13
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def gadmin_member_list(message, group):
    """
    グループのメンバー一覧を返す

    :param key: グループのメールアドレス(@の前の部分)
    """
    service = _get_service()
    group = _get_default_domain_email(group)
    try:
        members_list = service.members().list(groupKey=group).execute()
    except HttpError:
        botsend(message, '`{}` に合致するグループはありません'.format(group))
        return

    count = 0
    msg = ''
    for member in members_list.get('members', []):
        email = member['email']
        msg += '- {}\n'.format(email)
        count += 1
    msg = '*{}* グループのメンバー({}ユーザー)\n'.format(group, count) + msg
    botsend(message, msg) 
Example #14
Source File: app_engine.py    From loaner with Apache License 2.0 6 votes vote down vote up
def get(self):
    """Retrieves the information associated with a given Project ID.

    Returns:
      A dictionary object representing a deployed Google App Engine application
          (Type: google.appengine.v1.Application).

    Raises:
      NotFoundError: when unable to find a Google App Engine application for the
          provided Google Cloud Project ID.
    """
    try:
      return self._client.apps().get(appsId=self._config.project).execute()
    except errors.HttpError as err:
      logging.error(_GET_ERROR_MSG, self._config.project, err)
      raise NotFoundError(_GET_ERROR_MSG % (self._config.project, err)) 
Example #15
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _gadmin_group_delete(message, service, group):
    """
    指定したグループを削除する

    :param service: Google API との接続
    :param group: グループのメールアドレス
    """
    try:
        result = service.groups().get(groupKey=group).execute()
        count = result['directMembersCount']
        if count != '0':
            # メンバーがいる場合は削除できない
            botsend(message, '''
`{group}` グループはメンバーがいるので削除できません
`$gadmin member delete {group} メールアドレス` コマンドでメンバーを削除してから実行してください
`$gadmin member list {group}` コマンドでメンバー一覧が確認できます
'''.format(group=group))
        else:
            service.groups().delete(groupKey=group).execute()
            botsend(message, '`{}` グループを削除しました'.format(group))
    except HttpError as e:
        botsend(message, 'グループの削除に失敗しました\n`{}`'.format(e))
        return 
Example #16
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def gadmin_alias_list(message, email):
    """
    指定したユーザーのエイリアスの一覧を返す

    :param email: メールアドレス
    """

    service = _get_service()
    email = _get_default_domain_email(email)
    try:
        result = service.users().aliases().list(userKey=email).execute()
        msg = ''
        aliases = result.get('aliases', [])
        if aliases:
            msg = '`{}` のエイリアス一覧\n'.format(email)
            msg += ', '.join('`{}`'.format(alias['alias']) for alias in aliases)
            botsend(message, msg)
        else:
            msg = '`{}` のエイリアスはありません'.format(email)
            botsend(message, msg)
    except HttpError as e:
        botsend(message, 'エイリアスの取得失敗しました\n`{}`'.format(e)) 
Example #17
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _gadmin_user_password_reset(service, message, email):
    """
    ユーザーのパスワードをリセットする

    :param service: Google API との接続
    :param email: メールアドレス
    """
    # パスワードを生成する
    password = _generate_password()
    body = {
        'password': password,
    }
    try:
        service.users().update(userKey=email, body=body).execute()
        botsend(message, 'ユーザー `{}` のパスワードをリセットしました'.format(email))
        # password を実行ユーザーにDMで伝える
        _send_password_on_dm(message, email, password)
    except HttpError as e:
        botsend(message, 'ユーザーパスワードのリセットに失敗しました\n`{}`'.format(e)) 
Example #18
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _gadmin_user_update(service, message, email, suspended):
    """
    ユーザーの情報を更新する

    :param service: Google API との接続
    :param email: メールアドレス
    :param suspended: ユーザーの状態、True or False
    """
    body = {
        'suspended': suspended,
    }
    try:
        service.users().update(userKey=email, body=body).execute()
        if suspended:
            botsend(message, 'ユーザー `{}` を停止しました'.format(email))
        else:
            botsend(message, 'ユーザー `{}` を再開しました'.format(email))
    except HttpError as e:
        botsend(message, 'ユーザー情報の更新に失敗しました\n`{}`'.format(e)) 
Example #19
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _gadmin_user_delete(service, message, email):
    """
    指定したユーザーを削除する

    :param service: Google API との接続
    :param email: メールアドレス
    """
    try:
        # 停止中のユーザーのみ削除対象とする
        result = service.users().get(userKey=email).execute()
        if not result['suspended']:
            botsend(message, 'ユーザーはアクティブなため削除できません\n'
                         '`$gadmin user suspend {}` でユーザーを停止してから削除してください'.format(email))
        else:
            service.users().delete(userKey=email).execute()
            botsend(message, 'ユーザー `{}` を削除しました'.format(email))
    except HttpError as e:
        botsend(message, 'ユーザーの削除に失敗しました\n`{}`'.format(e)) 
Example #20
Source File: dsub_util.py    From dsub with Apache License 2.0 6 votes vote down vote up
def _prefix_exists_in_gcs(gcs_prefix, credentials=None):
  """Check whether there is a GCS object whose name starts with the prefix.

  Since GCS doesn't actually have folders, this is how we check instead.

  Args:
    gcs_prefix: The path; should start with 'gs://'.
    credentials: Optional credential to be used to load the file from gcs.

  Returns:
    True if the prefix matches at least one object in GCS.

  Raises:
    errors.HttpError: if it can't talk to the server
  """
  gcs_service = _get_storage_service(credentials)

  bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1)
  # documentation in
  # https://cloud.google.com/storage/docs/json_api/v1/objects/list
  request = gcs_service.objects().list(
      bucket=bucket_name, prefix=prefix, maxResults=1)
  response = request.execute()
  return response.get('items', None) 
Example #21
Source File: dsub_util.py    From dsub with Apache License 2.0 6 votes vote down vote up
def _file_exists_in_gcs(gcs_file_path, credentials=None):
  """Check whether the file exists, in GCS.

  Args:
    gcs_file_path: The target file path; should have the 'gs://' prefix.
    credentials: Optional credential to be used to load the file from gcs.

  Returns:
    True if the file's there.
  """
  gcs_service = _get_storage_service(credentials)

  bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)
  request = gcs_service.objects().get(
      bucket=bucket_name, object=object_name, projection='noAcl')
  try:
    request.execute()
    return True
  except errors.HttpError:
    return False 
Example #22
Source File: gmail.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_message(
            self,
            msg_id,
            user_id='me'):
        """Get a Message with given ID.

        :param msg_id: ID of Message to delete.
        :param user_id: User's email address. The special value "me"
            can be used to indicate the authenticated user.
        :return: A Message.
        :rtype: dict
        """
        self.connect()
        ret = {}
        try:
            ret = self.client.users().messages().get(
                userId=user_id,
                id=msg_id
            ).execute()
        except (socks.HTTPError, errors.HttpError) as error:
            logger.error('An error occurred: %s', error)
        else:
            logger.info('Message snippet: %s', ret.get('snippet'))
        return ret 
Example #23
Source File: gmail.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_message(
            self,
            msg_id,
            user_id='me'):
        """Delete a Message.

        :param msg_id: ID of Message to delete.
        :param user_id: User's email address. The special value "me"
            can be used to indicate the authenticated user.
        :rtype: `None`
        """
        self.connect()
        try:
            self.client.users().messages().delete(
                userId=user_id,
                id=msg_id
            ).execute()
        except (socks.HTTPError, errors.HttpError) as error:
            logger.error('An error occurred: %s', error)
        else:
            logger.info('Message with id: %s deleted successfully.', msg_id) 
Example #24
Source File: pubsub.py    From iris with MIT License 6 votes vote down vote up
def publish(client, body, topic):
    """Publish a message to a Pub/Sub topic."""
    project = 'projects/{}'.format(utils.get_project_id())
    dest_topic = project + '/topics/' + topic

    @backoff.on_exception(
        backoff.expo, HttpError, max_tries=3, giveup=utils.fatal_code)
    def _do_request():
        client.projects().topics().publish(
            topic=dest_topic, body=body).execute()

    try:
        _do_request()
    except HttpError as e:
        logging.error(e)
        raise PubSubException(e) 
Example #25
Source File: directory.py    From loaner with Apache License 2.0 6 votes vote down vote up
def disable_chrome_device(self, device_id):
    """Disable a Chrome device within an organization.

    Args:
      device_id: String, The unique Chrome device id.

    Raises:
      DirectoryRPCError: An error when the RPC call to the directory API fails.
    """
    logging.info('Disabling chrome device %s.', device_id)
    try:
      self._client.chromeosdevices().action(
          customerId=constants.CUSTOMER_ID,
          resourceId=device_id,
          body={
              'action': 'disable'
          }).execute()
    except errors.HttpError as err:
      if err.resp.status == httplib.PRECONDITION_FAILED:
        raise DeviceAlreadyDisabledError(err.resp.reason)
      logging.error(
          'Directory API call to disable Chrome device failed with a %s '
          'exception because %s.', str(type(err)), err.resp.reason)
      raise DirectoryRPCError(err.resp.reason) 
Example #26
Source File: directory.py    From loaner with Apache License 2.0 6 votes vote down vote up
def reenable_chrome_device(self, device_id):
    """Re-enable a Chrome device within an organization.

    Args:
      device_id: String, The unique Chrome device id.

    Raises:
      DirectoryRPCError: An error when the RPC call to the directory API fails.
    """
    logging.info('Re-enabling chrome device %s.', device_id)
    try:
      self._client.chromeosdevices().action(
          customerId=constants.CUSTOMER_ID,
          resourceId=device_id,
          body={
              'action': 'reenable'
          }).execute()
    except errors.HttpError as err:
      logging.error(
          'Directory API call to reenable Chrome device failed with a %s '
          'exception because %s.', str(type(err)), err.resp.reason)
      raise DirectoryRPCError(err.resp.reason) 
Example #27
Source File: directory.py    From loaner with Apache License 2.0 6 votes vote down vote up
def given_name(self, user_email):
    """Get the given name of a user.

    Args:
      user_email: String, The email address of the user.

    Returns:
      A string containing the given name for a user.

    Raises:
      DirectoryRPCError: An error when the RPC call to the directory API fails.
    """
    try:
      return self._client.users().get(
          userKey=user_email,
          fields=constants.USER_NAME_FIELDS_MASK).execute()['name']['givenName']
    except errors.HttpError as err:
      logging.error(
          'Directory API given_name failed with a %s exception because %s.',
          str(type(err)), err.resp.reason)
      raise DirectoryRPCError(err.resp.reason)
    except KeyError as err:
      logging.info(
          'The given name for this user (%s) does not exist.', user_email)
      raise GivenNameDoesNotExistError(str(err)) 
Example #28
Source File: directory.py    From loaner with Apache License 2.0 6 votes vote down vote up
def _users_in_group(self, group_email, page_token=None):
    """List the users in a group.

    Args:
      group_email: String, The email address of the group for whose users to
        return.
      page_token: String, The optional page token to query for.

    Returns:
      A dictionary based on a JSON object of kind admin#directory#members.
        For reference: https://goo.gl/YXiFq1

    Raises:
      DirectoryRPCError: An error when the RPC call to the directory API fails.
    """
    try:
      return self._client.members().list(
          groupKey=group_email,
          pageToken=page_token,
          fields=constants.GROUP_MEMBER_FIELDS_MASK).execute()
    except errors.HttpError as err:
      logging.error(
          'Directory API group members failed with a %s exception because %s.',
          str(type(err)), err.resp.reason)
      raise DirectoryRPCError(err.resp.reason) 
Example #29
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _gadmin_group_insert(message, service, group, name):
    """
    指定したグループを追加する

    :param service: Google API との接続
    :param group: グループのメールアドレス
    :param name: グループの名前
    """
    body = {
        'name': name,
        'email': group,
    }
    try:
        service.groups().insert(body=body).execute()
    except HttpError as e:
        botsend(message, 'グループの追加に失敗しました\n`{}`'.format(e))
        return
    botsend(message, '`{}` グループを追加しました'.format(group))
    botsend(message, '`$gadmin member insert {} メールアドレス` コマンドでメンバーを追加してください'.format(group)) 
Example #30
Source File: directory.py    From loaner with Apache License 2.0 5 votes vote down vote up
def move_chrome_device_org_unit(self, device_id, org_unit_path):
    """Move a Chrome device into a new Organizational Unit.

    Args:
      device_id: String, The unique Chrome DeviceId.
      org_unit_path: String, The OrgUnitPath for the Organizational Unit to
        which this Chrome device should now belong.

    Raises:
      DirectoryRPCError: An error when the RPC call to the directory API fails.
    """
    # This is here to catch false device ids. The moveDevicesToOu does not fail
    # for devices that do not exist in this organization.
    self.get_chrome_device(device_id)
    logging.info(
        'Moving device with device ID %r to OU %r.', device_id, org_unit_path)
    try:
      self._client.chromeosdevices().moveDevicesToOu(
          customerId=constants.CUSTOMER_ID,
          orgUnitPath=org_unit_path,
          body={
              'deviceIds': [device_id]
          }).execute()
    except errors.HttpError as err:
      logging.error(
          'Directory API move Chrome device Org Unit failed with a %s '
          'exception because %s.', str(type(err)), err.resp.reason)
      raise DirectoryRPCError(err.resp.reason)