Python apiclient.discovery.build() Examples

The following are 30 code examples of apiclient.discovery.build(). 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 apiclient.discovery , 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_upload.py    From Gdrivedownloader with MIT License 7 votes vote down vote up
def upload_file(file_path, file_name, mime_type):
# Create Google Drive service instance
    drive_service = build('drive', 'v2', http=http)
# File body description
    media_body = MediaFileUpload(file_path,
                                 mimetype=mime_type,
                                 resumable=True)
    body = {
        'title': file_name,
        'description': 'backup',
        'mimeType': mime_type,
    }
# Permissions body description: anyone who has link can upload
# Other permissions can be found at https://developers.google.com/drive/v2/reference/permissions
    permissions = {
        'role': 'reader',
        'type': 'anyone',
        'value': None,
        'withLink': True
    }
# Insert a file
    file = drive_service.files().insert(body=body, media_body=media_body).execute()
# Insert new permissions
    drive_service.permissions().insert(fileId=file['id'], body=permissions).execute()
# Define file instance and get url for download
    file = drive_service.files().get(fileId=file['id']).execute()
    download_url = file.get('webContentLink')
    return download_url 
Example #3
Source File: itunes-rating.py    From app-store-reviews-and-translations with Apache License 2.0 6 votes vote down vote up
def translate(translate_text, key, log_f, hn):

    lang_code = "en"

    service = build('translate', 'v2', developerKey=key)
    if translate_text!=None:
        try:
            result      = service.translations().list(target=lang_code,q=translate_text).execute()
            translation = result['translations'][0]['translatedText']
        except:
            print "There was an error with the translation."
            log_f.write("%s %s itunes-rating: There was an error with the translation.\n" % (log_date(), hn))
            translation = None
    else:
        translation = None

    return translation

# create class 
Example #4
Source File: gcp_util.py    From tensorflow-recommendation-wals with Apache License 2.0 6 votes vote down vote up
def _delete_resources(bucket_name, resources, credentials):
    """Deletes the specified resources from the given bucket.

    Resources are represented as described in
    https://cloud.google.com/storage/docs/json_api/v1/objects#resource

    Args:
        bucket_name: a string specifying the bucket from which to
            delete
        resources: a list of resources
        credentials: oauth2client.Credentials to be used for
            authentication
    """
    logging.info("Deleting %s resources.", len(resources))
    service = discovery.build('storage', 'v1', credentials=credentials)
    for r in resources:
        try:
            service.objects().delete(
                bucket=bucket_name,
                object=r['name']).execute()
        except apiclient.errors.HttpError as e:
            logging.warning('Error deleting %s: %s', r, e) 
Example #5
Source File: google_analytics_hook.py    From google_analytics_plugin with Apache License 2.0 6 votes vote down vote up
def get_service_object(self, name):
        service = GoogleAnalyticsHook._services[name]

        if self.connection.password:
            credentials = AccessTokenCredentials(self.connection.password,
                                                 'Airflow/1.0')
        elif hasattr(self, 'client_secrets'):
            credentials = ServiceAccountCredentials.from_json_keyfile_dict(self.client_secrets,
                                                                           service.scopes)

        elif hasattr(self, 'file_location'):
            credentials = ServiceAccountCredentials.from_json_keyfile_name(self.file_location,
                                                                           service.scopes)
        else:
            raise ValueError('No valid credentials could be found')

        return build(service.name, service.version, credentials=credentials) 
Example #6
Source File: gcp_util.py    From tensorflow-recommendation-wals with Apache License 2.0 6 votes vote down vote up
def empty_gcs_bucket(bucket_name, credentials):
    """Attempts to delete all objects in a bucket.

    If concurrent object creations occur while the bucket is being
    emptied, those objects may not be deleted and may cause bucket
    deletion to fail.

    Args:
        bucket_name: a string specifying the bucket to empty
        credentials: oauth2client.Credentials to be used for
            authentication
    """
    logging.info("Emptying GCS bucket: %s", bucket_name)
    service = discovery.build('storage', 'v1', credentials=credentials)
    response = service.objects().list(bucket=bucket_name).execute()
    _delete_resources(bucket_name, response.get('items', []), credentials)
    while 'nextPageToken' in response:
        response = service.objects().list(
            bucket=bucket_name, pageToken=response['nextPageToken']).execute()
        _delete_resources(bucket_name, response.get('items', []), credentials) 
Example #7
Source File: gcp_util.py    From tensorflow-recommendation-wals with Apache License 2.0 6 votes vote down vote up
def set_sql_root_password(root_pw, instance_name, project, credentials):
    """Attempts to set the root SQL password in a Cloud SQL instance.

    Args:
        root_pw: A string specifying the root password to set in the
            Cloud SQL instance.
        instance_name: A string specifying the name of the Cloud SQL
            instance
        project: a string specifying the GCP project in which to create
            the instance
        credentials: oauth2client.Credentials to be used for
            authentication

    Returns:
        True if the instance's root password was successfully set; False
        otherwise.
    """
    service = discovery.build('sqladmin', 'v1beta4', credentials=credentials)
    request = service.users().update(
        project=project, instance=instance_name, host='%', name='root',
        body={'password': root_pw})

    logging.info('Waiting for Cloud SQL root password set: %s', instance_name)
    return _wait_for_operation(request,
                               _cloud_sql_op_poller_factory(service, project)) 
Example #8
Source File: quickstart.py    From pyrobotlab with Apache License 2.0 6 votes vote down vote up
def main():
    """Shows basic usage of the Google Calendar API.

    Creates a Google Calendar API service object and outputs a list of the next
    10 events on the user's calendar.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    eventsResult = service.events().list(
        calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
        orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary']) 
Example #9
Source File: auth.py    From cloudaux with Apache License 2.0 6 votes vote down vote up
def _build_google_client(service, api_version, http_auth):
    """
    Google build client helper.

    :param service: service to build client for
    :type service: ``str``

    :param api_version: API version to use.
    :type api_version: ``str``

    :param http_auth: Initialized HTTP client to use.
    :type http_auth: ``object``

    :return: google-python-api client initialized to use 'service'
    :rtype: ``object``
    """
    client = build(service, api_version, http=http_auth)
    return client 
Example #10
Source File: screen.py    From RPi-InfoScreen-Kivy with GNU General Public License v3.0 6 votes vote down vote up
def update(self, *args):

        # Try and authorise the machine
        if not self.credentials:
            self.credentials = get_credentials()

        # If we authorised successfully we can show a calendar
        if self.credentials:

            # Connect to the Google API
            http = self.credentials.authorize(httplib2.Http())
            self.calendar = discovery.build('calendar', 'v3', http=http)

            # Get the calendars
            self.calendarlist = self.getCalendars()

            # If we've got calendars, display them
            if self.calendarlist:
                self.drawCalendars() 
Example #11
Source File: target_gsheet.py    From target-gsheet with GNU Affero General Public License v3.0 6 votes vote down vote up
def main():
    with open(flags.config) as input:
        config = json.load(input)
        
    if not config.get('disable_collection', False):
        logger.info('Sending version information to stitchdata.com. ' +
                    'To disable sending anonymous usage data, set ' +
                    'the config parameter "disable_collection" to true')
        threading.Thread(target=collect).start()

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheet = get_spreadsheet(service, config['spreadsheet_id'])

    input = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
    state = None
    state = persist_lines(service, spreadsheet, input)
    emit_state(state)
    logger.debug("Exiting normally") 
Example #12
Source File: google-translate.py    From app-store-reviews-and-translations with Apache License 2.0 6 votes vote down vote up
def translate(translate_text, key):

    lang_code = "en"

    service = build('translate', 'v2', developerKey=key)
    if translate_text!=None:
        try:
            result = service.translations().list(target=lang_code,q=translate_text).execute()
            translation = result['translations'][0]['translatedText']
        except:
            print "There was an error with the translation."
            translation = None
    else:
        translation = None

    return translation


#------------------------------------------------ 
Example #13
Source File: google-play-rating.py    From app-store-reviews-and-translations with Apache License 2.0 6 votes vote down vote up
def translate(translate_text, key, log_f, hn):

    lang_code = "en"

    service = build('translate', 'v2', developerKey=key)
    if translate_text!=None:
        try:
            result = service.translations().list(target=lang_code,q=translate_text).execute()
            translation = result['translations'][0]['translatedText']
        except:
            print "There was an error with the translation."
            log_f.write("%s %s android-rating: There was an error with the translation.\n" % (log_date(), hn))
            translation = None
    else:
        translation = None

    return translation

# create class 
Example #14
Source File: archive_deployment_packages.py    From Lecture-Series-Python with MIT License 6 votes vote down vote up
def main():
    # Initialize and authorize Google Drive API
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    # Get local config
    local_config = get_json_config('config.json')

    deployment_package_dir = local_config['deployment_package_dir']
    archive_dir = local_config['archive_dir']
    deployment_package_backup_dir = local_config['deployment_package_backup_dir']
    archive_backup_dir = local_config['archive_backup_dir']

    if not deployment_package_dir and not archive_dir:
        print('Script is not configured properly.')
        return 1

    # Archive the directories in deployment package dir
    archive_dirs(os.listdir(deployment_package_dir),
                 deployment_package_dir, archive_dir,
                 deployment_package_backup_dir)

    # Upload to Google Drive
    upload_archives(os.listdir(archive_dir), archive_dir, service, archive_backup_dir) 
Example #15
Source File: google_api.py    From pyconjpbot with MIT License 6 votes vote down vote up
def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    now = datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
    print('直近の5件のイベントを表示')
    eventsResult = service.events().list(
        calendarId='primary', timeMin=now, maxResults=5, singleEvents=True,
        orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary']) 
Example #16
Source File: utils.py    From twitter-for-bigquery with Apache License 2.0 6 votes vote down vote up
def get_bq():
        
        if Utils.BQ_CLIENT:
            
            return Utils.BQ_CLIENT
        
        BQ_CREDENTIALS = None
        
        # If runing on Google stack, authenticate natively
        if Utils.isGae():
            
            from oauth2client import appengine
            BQ_CREDENTIALS = appengine.AppAssertionCredentials(scope='https://www.googleapis.com/auth/bigquery')

        else:
            
            from oauth2client.client import SignedJwtAssertionCredentials
            KEY = Utils.read_file(config.KEY_FILE)
            BQ_CREDENTIALS = SignedJwtAssertionCredentials(config.SERVICE_ACCOUNT, KEY, 'https://www.googleapis.com/auth/bigquery')
    
        BQ_HTTP = BQ_CREDENTIALS.authorize(httplib2.Http())
        Utils.BQ_CLIENT = build('bigquery', 'v2', http=BQ_HTTP)
        
        return  Utils.BQ_CLIENT 
Example #17
Source File: bigquery.py    From deezer-bigquery with MIT License 6 votes vote down vote up
def build_service(secret, credentials):
    """
    Build reference to a BigQuery service / API.
    
    Parameters
    ----------
    secret : string
        Path to the secret files
    credentials : string
        Path to the credentials files

    Returns
    -------
    out : object
        The service reference
    """
    flow = flow_from_clientsecrets(secret, scope="https://www.googleapis.com/auth/bigquery")
    storage = Storage(credentials)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, tools.argparser.parse_args([]))

    http = credentials.authorize(httplib2.Http())
    return build("bigquery", "v2", http=http) 
Example #18
Source File: GoogleCloudFunctions.py    From content with MIT License 6 votes vote down vote up
def __init__(self, service_name: str, service_version: str, client_secret: str, scopes: list, proxy: bool,
                 insecure: bool, **kwargs):
        """
        :param service_name: The name of the service. You can find this and the service  here
         https://github.com/googleapis/google-api-python-client/blob/master/docs/dyn/index.md
        :param service_version:The version of the API.
        :param client_secret: A string of the credentials.json generated
        :param scopes: The scope needed for the project. Might be different per function.
        (i.e. ['https://www.googleapis.com/auth/cloud-platform'])
        :param proxy:
        :param insecure:
        :param kwargs:
        """
        self.project = kwargs.get('project', '')
        self.region = kwargs.get('region', '-')
        credentials = service_account.ServiceAccountCredentials.from_json_keyfile_dict(client_secret, scopes=scopes)
        if proxy or insecure:
            http_client = credentials.authorize(self.get_http_client_with_proxy(proxy, insecure))
            self.service = discovery.build(service_name, service_version, http=http_client)
        else:
            self.service = discovery.build(service_name, service_version, credentials=credentials)

    # disable-secrets-detection-start 
Example #19
Source File: api.py    From django-torina-blog with MIT License 6 votes vote down vote up
def initialize_analyticsreporting():
    """Initializes an analyticsreporting service object.

    Returns:   analytics an authorized analyticsreporting service
    object.

    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(
        settings.SERVICE_ACCOUNT_EMAIL, settings.KEY_FILE_LOCATION,
        scopes=SCOPES
    )

    http = credentials.authorize(httplib2.Http())

    # Build the service object.
    analytics = build('analytics', 'v4', http=http,
                      discoveryServiceUrl=DISCOVERY_URI)

    return analytics 
Example #20
Source File: event1.py    From pyrobotlab with Apache License 2.0 5 votes vote down vote up
def event():

  try:
      import argparse
      flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  except ImportError:
      flags = None

  # If modifying these scopes, delete your previously saved credentials
  # at ~/.credentials/calendar-python-quickstart.json
  SCOPES = 'https://www.googleapis.com/auth/calendar'
  store = file.Storage('storage.json')
  creds = store.get()
  if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store, flags) \
	    if flags else tools.run(flow, store)
  CAL = build('calendar', 'v3', http=creds.authorize(Http()))

  SUBJECT = 'teste azul'

  GMT_OFF = '-04:00'
  EVENT = {
    'summary' : SUBJECT,
    'start' : {'dateTime': '2016-08-12T19:00:00%s' % GMT_OFF},
    'end' : {'dateTime': '2016-08-12T22:00:00%s' % GMT_OFF},
    'attendees': [
      
    ],
  }
    
  e = CAL.events().insert(calendarId='primary',
	  sendNotifications=True, body=EVENT).execute()

  print('''*** %r event added:
    Start: %s
    End:   %s''' % (e['summary'].encode('utf-8'),
	  e['start']['dateTime'], e['end']['dateTime'])) 
Example #21
Source File: authentication.py    From go-links with Apache License 2.0 5 votes vote down vote up
def get_user_email(oauth_credentials):
  http = httplib2.Http()
  http = oauth_credentials.authorize(http)

  user_info = build('oauth2', 'v2').tokeninfo().execute(http)

  if not user_info['verified_email']:
    return None

  return user_info['email'].lower() 
Example #22
Source File: support.py    From mirandum with Apache License 2.0 5 votes vote down vote up
def run_subs(ffu):
    storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential')
    credential = storage.get()
    if credential is None or credential.invalid == True:
        raise Exception("invalid credentials")
    http = httplib2.Http()
    http = credential.authorize(http)
    service = discovery.build('gmail', 'v1', http)
    output = ListRecentMessagesMatchingQuery(service, "me", '"has subscribed to you"')
    added = 0
    for item in output:
        if SubEvent.objects.filter(external_id=item['id'], updater=ffu).count():
            break
        message = GetMessage(service, "me", item['id'])
        headers = message['payload']['headers']
        f, s, d = '', '', ''
        for header in headers:
            if header['name'] == "From": f = header['value']
            if header['name'] == "Subject": s = header['value']
            if header['name'] == "Date": d = header['value']
        if 'noreply@youtube.com' in f:
            s = s.strip().replace(" has subscribed to you on YouTube!", "")
            try:
                e = SubEvent(external_id=item['id'], details = s, updater=ffu)
                e.save()
                added += 1
            except Exception, E:
                print "Failed to create specific subevent for %s: \n    %s: %s" % (ffu.id, type(E), E) 
Example #23
Source File: gdrive.py    From fb2mobi with MIT License 5 votes vote down vote up
def __init__(self, credential_file, executable_path):
        self.credential_file = credential_file
        self.executable_path = executable_path

        self.http = httplib2.Http(ca_certs=os.path.join(self.executable_path, 'cacerts.txt'))
        credentials = self.get_credentials()
        self.http = credentials.authorize(self.http)
        self.service = discovery.build('drive', 'v3', http=self.http) 
Example #24
Source File: group_sync.py    From professional-services with Apache License 2.0 5 votes vote down vote up
def _get_service_reference(self, admin_email):
    """Instantiates a connection to the API.

    Args:
      admin_email: a G Suite or Cloud Identity administrator account to
        impersonate.

    Returns:
      A reference to an API Service object, ready to call APIs.
    """
    if self.use_cloud_identity:
      scopes = [
          'https://www.googleapis.com/auth/cloud-identity.groups.readonly'
      ]
    else:
      scopes = [
          'https://www.googleapis.com/auth/admin.directory.group',
      ]

    credentials = auth_util.get_credentials(admin_email, scopes)
    if self.use_cloud_identity:
      service = build('cloudidentity', 'v1', credentials=credentials)
    else:
      service = build('admin', 'directory_v1', credentials=credentials)

    return service 
Example #25
Source File: base.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def test_connectivity(self):
    """Executes a basic API call with no side-effects to ensure we can talk to Google."""
    service = discovery.build('discovery', 'v1', http=self.connection)
    request = service.apis().list(name="discovery", preferred=True)
    response = gutils.execute_request(request)
    # logger.debug("connectivity test response:\n{:s}", pprint.pformat(response))
    return response 
Example #26
Source File: upload.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def get_authenticated_service():
    upload_scope = 'https://www.googleapis.com/auth/youtube.upload'
    flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=upload_scope)
    storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        flags = argparser.parse_args(args=['--noauth_local_webserver'])
        credentials = run_flow(flow, storage, flags)

    return build('youtube', 'v3', http=credentials.authorize(httplib2.Http()), cache_discovery=False) 
Example #27
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def get_service(self, service, version, scopes=None):
        import httplib2
        from apiclient import discovery

        if scopes is None:
            scopes = getattr(self, 'scopes') if hasattr(self, 'scopes') else []

        scopes = ' '.join(sorted(scopes))
        credentials = self.credentials[scopes]
        http = credentials.authorize(httplib2.Http())
        return discovery.build(service, version, http=http, cache_discovery=False)


# vim:sw=4:ts=4:et: 
Example #28
Source File: client.py    From frost with Mozilla Public License 2.0 5 votes vote down vote up
def _service(self, product, version="v1"):
        """Internal helper around google client lib's build service func"""
        return build_service(product, version) 
Example #29
Source File: base.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def _get_mobile_devices_by_email(self, email, batch_size=1000):
    service = discovery.build('admin', 'directory_v1', http=self.connection)
    resource = service.mobiledevices()
    request = resource.list(customerId='my_customer', query='email:{!s}'.format(email),
        projection="FULL", maxResults=batch_size)
    mobile_devices = gutils.execute_batch(resource, request, 'mobiledevices')
    # logger.debug("found {:d} mobile devices", len(mobile_devices))
    # logger.debug("mobile devices:\n{!s}", pprint.pformat(mobile_devices))
    return [self._process_mobile_device(raw) for raw in mobile_devices] 
Example #30
Source File: client.py    From frost with Mozilla Public License 2.0 5 votes vote down vote up
def build_directory_client(self):
        # TODO: Support passing creds name as config option
        credentials = get_credentials(CREDS_NAME)
        http = credentials.authorize(httplib2.Http())
        return discovery.build("admin", "directory_v1", http=http)