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)
python类get_application_default()的实例源码
def get_application_default():
"""Get the Application Default Credentials for the current environment.
Raises:
ApplicationDefaultCredentialsError: raised when the credentials
fail to be retrieved.
"""
return GoogleCredentials._get_implicit_credentials()
def get_client():
"""Creates Pub/Sub client and returns it."""
if not hasattr(client_store, 'client'):
client_store.client = get_client_from_credentials(
GoogleCredentials.get_application_default())
return client_store.client
def _googleauth(key_file=None, scopes=[], user_agent=None):
"""
Google http_auth helper.
If key_file is not specified, default credentials will be used.
If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES
:param key_file: path to key file to use. Default is None
:type key_file: ``str``
:param scopes: scopes to set. Default is DEFAUL_SCOPES
:type scopes: ``list``
:param user_agent: User Agent string to use in requests. Default is None.
:type http_auth: ``str`` or None
:return: HTTPLib2 authorized client.
:rtype: :class: `HTTPLib2`
"""
if key_file:
if not scopes:
scopes = DEFAULT_SCOPES
creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,
scopes=scopes)
else:
creds = GoogleCredentials.get_application_default()
http = Http()
if user_agent:
http = set_user_agent(http, user_agent)
http_auth = creds.authorize(http)
return http_auth
def __init__(self, model_directory):
self.model_directory = model_directory
self.http = self._create_http()
self.service = googleapiclient.discovery.build(
'bigquery',
'v2',
credentials=GoogleCredentials.get_application_default(),
http=self.http
)
def _get_storage_service(credentials):
"""Get a storage client using the provided credentials or defaults."""
if credentials is None:
credentials = GoogleCredentials.get_application_default()
return discovery.build('storage', 'v1', credentials=credentials)
def _setup_service(cls, credentials=None):
"""Configures genomics API client.
Args:
credentials: credentials to be used for the gcloud API calls.
Returns:
A configured Google Genomics API client with appropriate credentials.
"""
if not credentials:
credentials = GoogleCredentials.get_application_default()
return cls._do_setup_service(credentials)
def __init__(self, api_discovery_file='vision_api.json'):
self.credentials = GoogleCredentials.get_application_default()
self.service = discovery.build(
'vision', 'v1', credentials=self.credentials,
discoveryServiceUrl=DISCOVERY_URL)
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent,
revoke_uri=oauth2client.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
oauth2client.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)
def from_json(cls, json_data):
# TODO(issue 388): eliminate the circularity that is the reason for
# this non-top-level import.
from oauth2client import service_account
data = json.loads(_helpers._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 service_account.ServiceAccountCredentials.from_json(data)
elif (data['_module'] == 'oauth2client.service_account' and
data['_class'] == '_JWTAccessCredentials'):
return service_account._JWTAccessCredentials.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
def get_application_default():
"""Get the Application Default Credentials for the current environment.
Raises:
ApplicationDefaultCredentialsError: raised when the credentials
fail to be retrieved.
"""
return GoogleCredentials._get_implicit_credentials()
def _create_client(self):
credentials = GoogleCredentials.get_application_default()
return discovery.build(
'vision', 'v1', credentials=credentials,
discoveryServiceUrl=DISCOVERY_URL)
def __init__(self, api_discovery_file='vision_api.json'):
self.credentials = GoogleCredentials.get_application_default()
self.service = discovery.build(
'vision', 'v1', credentials=self.credentials,
discoveryServiceUrl=DISCOVERY_URL)
def get_vision_service():
credentials = GoogleCredentials.get_application_default()
return discovery.build('vision', 'v1', credentials=credentials,
discoveryServiceUrl=DISCOVERY_URL)
# [END get_vision_service]
# [START identify_landmark]
def _create_tasks_client():
credentials = GoogleCredentials.get_application_default()
with open(
os.path.join(os.path.dirname(__file__), 'cloudtasks.json'), 'r') as f:
return build_from_document(f.read(), credentials=credentials)
def _get_iam_service():
"""Get the IAM service.
Returns:
An apiclient service object.
"""
credentials = GoogleCredentials.get_application_default()
return discovery.build(
serviceName="iam", version="v1", credentials=credentials)
def main(argv):
# Load label file
try:
new_lables = json.load(open(argv[1]))
except IndexError:
print("%s <lables.json> required!" % __file__, file=sys.stderr)
sys.exit(1)
except ValueError as err:
print("%s invalid json: %s" % (sys.argv[1], err), file=sys.stderr)
sys.exit(1)
# Pull defaults from metadata
metadata = get_metadata()
project, zone = itemgetter(1, 3)(metadata['zone'].split("/"))
instance_name = metadata['name']
# Google Creds
creds = GoogleCredentials.get_application_default()
# Describe Instance
conn = discovery.build('compute', 'beta', credentials=creds)
instance = conn.instances().get(project=project, zone=zone,
instance=instance_name).execute()
# Label Instance
label(instance['selfLink'], creds.get_access_token().access_token,
label_merge(instance['labels'] if 'labels' in instance else {},
instance["labelFingerprint"], new_lables))
# Label Disks
for i in instance['disks']:
# Skip local disk
if 'source' not in i:
continue
disk = conn.disks().get(project=project, zone=zone,
disk=i['source'].split('/')[-1]).execute()
label(disk['selfLink'], creds.get_access_token().access_token,
label_merge(disk['labels'] if 'labels' in disk else {},
disk["labelFingerprint"], new_lables))
def get_google_auth(service, version='v2'):
credentials = GoogleCredentials.get_application_default()
service_conn = discovery.build(service, version, credentials=credentials)
return service_conn
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')
def call_google_nlp(text):
"""Use the NL API to analyze the given text string, and returns the
response from the API. Requests an encodingType that matches
the encoding used natively by Python. Raises an
errors.HTTPError if there is a connection problem.
"""
# TODO check cred exists ....
# check GOOGLE_APPLICATION_CREDENTIALS
credentials = GoogleCredentials.get_application_default()
scoped_credentials = credentials.create_scoped(
['https://www.googleapis.com/auth/cloud-platform'])
http = httplib2.Http()
scoped_credentials.authorize(http)
service = discovery.build(
'language', 'v1beta1', http=http)
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text
},
'features': {
# 'extract_syntax': True,
'extractEntities': True
},
'encodingType': get_native_encoding_type(),
}
request = service.documents().annotateText(body=body)
return request.execute()