本文整理汇总了Python中apiclient.discovery.build方法的典型用法代码示例。如果您正苦于以下问题:Python discovery.build方法的具体用法?Python discovery.build怎么用?Python discovery.build使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类apiclient.discovery
的用法示例。
在下文中一共展示了discovery.build方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_connection
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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))
示例2: build_service
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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)
示例3: main
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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'])
示例4: translate
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
示例5: translate
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
示例6: translate
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
#------------------------------------------------
示例7: get_service_object
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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)
示例8: upload_file
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
示例9: __init__
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
示例10: initialize_analyticsreporting
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
示例11: _build_google_client
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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
示例12: main
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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'])
示例13: empty_gcs_bucket
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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)
示例14: _delete_resources
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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)
示例15: set_sql_root_password
# 需要导入模块: from apiclient import discovery [as 别名]
# 或者: from apiclient.discovery import build [as 别名]
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))