本文整理匯總了Python中oauth2client.client.GoogleCredentials.get_application_default方法的典型用法代碼示例。如果您正苦於以下問題:Python GoogleCredentials.get_application_default方法的具體用法?Python GoogleCredentials.get_application_default怎麽用?Python GoogleCredentials.get_application_default使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類oauth2client.client.GoogleCredentials
的用法示例。
在下文中一共展示了GoogleCredentials.get_application_default方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: validate
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def validate(self, parsed_args, client=None):
if not client:
credentials = GoogleCredentials.get_application_default().create_scoped(
['https://www.googleapis.com/auth/bigquery'])
client = bigquery.BigqueryV2(credentials=credentials)
project_id, dataset_id, table_id = bigquery_util.parse_table_reference(
parsed_args.input_table)
if not bigquery_util.table_exist(client, project_id, dataset_id, table_id):
raise ValueError('Table {}:{}.{} does not exist.'.format(
project_id, dataset_id, table_id))
if table_id.count(TABLE_SUFFIX_SEPARATOR) != 1:
raise ValueError(
'Input table {} is malformed - exactly one suffix separator "{}" is '
'required'.format(parsed_args.input_table,
TABLE_SUFFIX_SEPARATOR))
base_table_id = table_id[:table_id.find(TABLE_SUFFIX_SEPARATOR)]
sample_table_id = bigquery_util.compose_table_name(base_table_id,
SAMPLE_INFO_TABLE_SUFFIX)
if not bigquery_util.table_exist(client, project_id, dataset_id,
sample_table_id):
raise ValueError('Sample table {}:{}.{} does not exist.'.format(
project_id, dataset_id, sample_table_id))
示例2: __init__
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent,
revoke_uri=GOOGLE_REVOKE_URI):
"""Create an instance of GoogleCredentials.
This constructor is not usually called by the user, instead
GoogleCredentials objects are instantiated by
GoogleCredentials.from_stream() or
GoogleCredentials.get_application_default().
Args:
access_token: string, access token.
client_id: string, client identifier.
client_secret: string, client secret.
refresh_token: string, refresh token.
token_expiry: datetime, when the access_token expires.
token_uri: string, URI of token endpoint.
user_agent: string, The HTTP User-Agent to provide for this application.
revoke_uri: string, URI for revoke endpoint.
Defaults to GOOGLE_REVOKE_URI; a token can't be revoked if this is None.
"""
super(GoogleCredentials, self).__init__(
access_token, client_id, client_secret, refresh_token, token_expiry,
token_uri, user_agent, revoke_uri=revoke_uri)
示例3: gce_credentials_from_config
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def gce_credentials_from_config(gce_credentials_config=None):
"""
This function creates a proper GCE credentials object either from a passed
in configuration blob or, if this code is being run on a GCE instance, from
the default service account credentials associated with the VM.
:param dict gce_credentials_config: A credentials dict used to authenticate
against GCE. This should have the same content as the JSON blob you
download when you create a new key for a service account. If this is
``None``, then the instances implicit credentials will be used.
:returns: A GCE credentials object for use with the GCE API.
"""
if gce_credentials_config is not None:
credentials = ServiceAccountCredentials.from_p12_keyfile_buffer(
service_account_email=gce_credentials_config['client_email'],
file_buffer=BytesIO(gce_credentials_config['private_key']),
scopes=[
u"https://www.googleapis.com/auth/compute",
]
)
else:
credentials = GoogleCredentials.get_application_default()
return credentials
示例4: __init__
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def __init__(self, service_account_email, service_account_key,
google_api_url, http):
self.credentials = None
if service_account_email and service_account_key:
self.service_account_email = service_account_email
self.service_account_key = service_account_key
else:
self.service_account_email = ''
self.service_account_key = ''
try:
self.credentials = GoogleCredentials.get_application_default() \
.create_scoped(RpcHelper.GITKIT_SCOPE)
except Exception as e:
print('WARNING: unable to retrieve service account credentials.')
self.google_api_url = google_api_url + 'identitytoolkit/v3/relyingparty/'
if http is None:
self.http = httplib2.Http(client.MemoryCache())
else:
self.http = http
示例5: from_json
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def from_json(cls, json_data):
# TODO(issue 388): eliminate the circularity that is the reason for
# this non-top-level import.
from oauth2client.service_account import ServiceAccountCredentials
data = json.loads(_from_bytes(json_data))
# We handle service_account.ServiceAccountCredentials since it is a
# possible return type of GoogleCredentials.get_application_default()
if (data['_module'] == 'oauth2client.service_account' and
data['_class'] == 'ServiceAccountCredentials'):
return ServiceAccountCredentials.from_json(data)
token_expiry = _parse_expiry(data.get('token_expiry'))
google_credentials = cls(
data['access_token'],
data['client_id'],
data['client_secret'],
data['refresh_token'],
token_expiry,
data['token_uri'],
data['user_agent'],
revoke_uri=data.get('revoke_uri', None))
google_credentials.invalid = data['invalid']
return google_credentials
示例6: get_credentials
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def get_credentials(credential_file=None, credentials=None):
if credential_file:
return GoogleCredentials.from_stream(credential_file)
if credentials and credentials["type"] == "service_account":
return ServiceAccountCredentials_from_dict(credentials)
if credentials and credentials["type"] == "authorized_user":
return GoogleCredentials(
access_token=None,
client_id=credentials["client_id"],
client_secret=credentials["client_secret"],
refresh_token=credentials["refresh_token"],
token_expiry=None,
token_uri=GOOGLE_TOKEN_URI,
user_agent="pghoard")
return GoogleCredentials.get_application_default()
示例7: launch_job
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def launch_job(job_spec):
"""Launch job on ML Engine."""
project_id = "projects/{}".format(
text_encoder.native_to_unicode(cloud.default_project()))
credentials = GoogleCredentials.get_application_default()
cloudml = discovery.build("ml", "v1", credentials=credentials,
cache_discovery=False)
request = cloudml.projects().jobs().create(body=job_spec, parent=project_id)
request.execute()
示例8: make_request_fn
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def make_request_fn():
"""Returns a request function."""
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_version)
else:
request_fn = serving_utils.make_grpc_request_fn(
servable_name=FLAGS.servable_name,
server=FLAGS.server,
timeout_secs=FLAGS.timeout_secs)
return request_fn
示例9: update_bigquery_schema_on_append
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def update_bigquery_schema_on_append(schema_fields, output_table):
# type: (List[beam_bigquery.TableFieldSchema], str) -> None
"""Update BQ schema by combining existing one with a new one, if possible.
If table does not exist, do not need to update the schema.
TODO (yifangchen): Move the logic into validate().
"""
output_table_re_match = re.match(
r'^((?P<project>.+):)(?P<dataset>\w+)\.(?P<table>[\w\$]+)$',
output_table)
credentials = GoogleCredentials.get_application_default().create_scoped(
['https://www.googleapis.com/auth/bigquery'])
client = beam_bigquery.BigqueryV2(credentials=credentials)
try:
project_id = output_table_re_match.group('project')
dataset_id = output_table_re_match.group('dataset')
table_id = output_table_re_match.group('table')
existing_table = client.tables.Get(beam_bigquery.BigqueryTablesGetRequest(
projectId=project_id,
datasetId=dataset_id,
tableId=table_id))
except exceptions.HttpError:
return
new_schema = beam_bigquery.TableSchema()
new_schema.fields = _get_merged_field_schemas(existing_table.schema.fields,
schema_fields)
existing_table.schema = new_schema
try:
client.tables.Update(beam_bigquery.BigqueryTablesUpdateRequest(
projectId=project_id,
datasetId=dataset_id,
table=existing_table,
tableId=table_id))
except exceptions.HttpError as e:
raise RuntimeError('BigQuery schema update failed: %s' % str(e))
示例10: predict_cmle
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def predict_cmle(instances):
""" Use a deployed model to AI Platform to perform prediction
Args:
instances: list of json, csv, or tf.example objects, based on the serving function called
Returns:
response - dictionary. If no error, response will include an item with 'predictions' key
"""
credentials = GoogleCredentials.get_application_default()
service = discovery.build('ml', 'v1', credentials=credentials)
model_url = 'projects/{}/models/{}'.format(GCP_PROJECT, CMLE_MODEL_NAME)
if CMLE_MODEL_VERSION is not None:
model_url += '/versions/{}'.format(CMLE_MODEL_VERSION)
request_data = {
'instances': instances
}
response = service.projects().predict(
body=request_data,
name=model_url
).execute()
output = response
return output
示例11: launch_job
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def launch_job(job_spec):
"""Launch job on ML Engine."""
project_id = "projects/{}".format(
text_encoder.native_to_unicode(default_project()))
credentials = GoogleCredentials.get_application_default()
cloudml = discovery.build("ml", "v1", credentials=credentials,
cache_discovery=False)
request = cloudml.projects().jobs().create(body=job_spec, parent=project_id)
request.execute()
示例12: get
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def get(self):
is_cron = self.request.headers.get('X-Appengine-Cron', False)
# logging.info("is_cron is %s", is_cron)
# Comment out the following check to allow non-cron-initiated requests.
if not is_cron:
return 'Blocked.'
# These env vars are set in app.yaml.
PROJECT = os.environ['PROJECT']
BUCKET = os.environ['BUCKET']
TEMPLATE = os.environ['TEMPLATE_NAME']
# Because we're using the same job name each time, if you try to launch one
# job while another is still running, the second will fail.
JOBNAME = PROJECT + '-twproc-template'
credentials = GoogleCredentials.get_application_default()
service = build('dataflow', 'v1b3', credentials=credentials)
BODY = {
"jobName": "{jobname}".format(jobname=JOBNAME),
"gcsPath": "gs://{bucket}/templates/{template}".format(
bucket=BUCKET, template=TEMPLATE),
"parameters": {"timestamp": str(datetime.datetime.utcnow())},
"environment": {
"tempLocation": "gs://{bucket}/temp".format(bucket=BUCKET),
"zone": "us-central1-f"
}
}
dfrequest = service.projects().templates().create(
projectId=PROJECT, body=BODY)
dfresponse = dfrequest.execute()
logging.info(dfresponse)
self.response.write('Done')
示例13: start_gsuite_ingestion
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def start_gsuite_ingestion(session, config):
"""
Starts the GSuite ingestion process by initializing
:param session: The Neo4j session
:param config: A `cartography.config` object
:return: Nothing
"""
common_job_parameters = {
"UPDATE_TAG": config.update_tag,
}
try:
credentials = GoogleCredentials.from_stream(GSUITE_CREDS)
credentials = credentials.create_scoped(OAUTH_SCOPE)
credentials = credentials.create_delegated(GSUITE_DELEGATED_ADMIN)
except ApplicationDefaultCredentialsError as e:
logger.debug('Error occurred calling GoogleCredentials.get_application_default().', exc_info=True)
logger.error(
(
"Unable to initialize GSuite creds. If you don't have GSuite data or don't want to load "
'Gsuite data then you can ignore this message. Otherwise, the error code is: %s '
'Make sure your GSuite credentials are configured correctly, your credentials file (if any) is valid. '
'For more details see README'
),
e,
)
return
resources = _initialize_resources(credentials)
api.sync_gsuite_users(session, resources.admin, config.update_tag, common_job_parameters)
api.sync_gsuite_groups(session, resources.admin, config.update_tag, common_job_parameters)
示例14: _get_services
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def _get_services(self, version="v1"):
"""get version 1 of the google compute and storage service
Parameters
==========
version: version to use (default is v1)
"""
self._bucket_service = storage.Client()
creds = GoogleCredentials.get_application_default()
self._storage_service = discovery_build("storage", version, credentials=creds)
self._compute_service = discovery_build("compute", version, credentials=creds)
示例15: _get_services
# 需要導入模塊: from oauth2client.client import GoogleCredentials [as 別名]
# 或者: from oauth2client.client.GoogleCredentials import get_application_default [as 別名]
def _get_services(self, version="v1"):
"""get version 1 of the google compute and storage service
Parameters
==========
version: version to use (default is v1)
"""
self._bucket_service = storage.Client()
creds = GoogleCredentials.get_application_default()
self._storage_service = discovery_build("storage", version, credentials=creds)
self._build_service = discovery_build("cloudbuild", version, credentials=creds)