本文整理汇总了Python中oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_dict方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceAccountCredentials.from_json_keyfile_dict方法的具体用法?Python ServiceAccountCredentials.from_json_keyfile_dict怎么用?Python ServiceAccountCredentials.from_json_keyfile_dict使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2client.service_account.ServiceAccountCredentials
的用法示例。
在下文中一共展示了ServiceAccountCredentials.from_json_keyfile_dict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_gsheet_client
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def _init_gsheet_client():
with GoogleSheet._client_lock():
def _():
if config.GOOGLE_SERVICE_ACCOUNT is not None:
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json.loads(config.GOOGLE_SERVICE_ACCOUNT),
scopes=SCOPES)
else:
credentials = ServiceAccountCredentials.from_json_keyfile_name(
"avrae-google.json",
scopes=SCOPES)
return gspread.authorize(credentials)
try:
GoogleSheet.g_client = await asyncio.get_event_loop().run_in_executor(None, _)
except:
GoogleSheet._client_initializing = False
raise
GoogleSheet._token_expiry = datetime.datetime.now() + datetime.timedelta(
seconds=ServiceAccountCredentials.MAX_TOKEN_LIFETIME_SECS)
log.info("Logged in to google")
示例2: get_client
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def get_client():
"""Return client with connection to build apiary."""
# Connect using build apiary service account credentials.
build_apiary_service_account_private_key = db_config.get_value(
'build_apiary_service_account_private_key')
if not build_apiary_service_account_private_key:
logs.log(
'Android build apiary credentials are not set, skip artifact fetch.')
return None
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json.loads(build_apiary_service_account_private_key),
scopes='https://www.googleapis.com/auth/androidbuild.internal')
client = apiclient.discovery.build(
'androidbuildinternal',
'v2beta1',
credentials=credentials,
cache_discovery=False)
return client
示例3: get_service_object
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [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)
示例4: get_access_token_from_str
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def get_access_token_from_str(ga_key_content):
"""Get the access token from a string.
from https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/
Defines a method to get an access token from the credentials object.
The access token is automatically refreshed if it has expired.
"""
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
# Construct a credentials objects from the key data and OAuth2 scope.
keyDict = json.loads(ga_key_content.replace('\n', '').replace('\r', ''))
_credentials = ServiceAccountCredentials.from_json_keyfile_dict(
keyDict, SCOPE)
return _credentials.get_access_token().access_token
示例5: __init__
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def __init__(self, environment, cluster_name):
self.environment = environment
self.cluster_name = cluster_name
self.handler = environment.resource_handler.cast()
self.zone = environment.gcp_zone
self.project = self.handler.gpc_projects
self.credentials = ServiceAccountCredentials.from_json_keyfile_dict({
'client_email': self.handler.serviceaccount,
'private_key': self.handler.servicepasswd,
'type': 'service_account',
'client_id': None,
'private_key_id': None,
})
self.container_client = self.get_client('container')
self.compute_client = self.get_client('compute')
示例6: get_spreadsheet
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def get_spreadsheet(credentials, doc_id, tab_id):
"""
Inputs params:
* credentials
* doc_id
* tab_id
Returns a gspread's worksheet object.
"""
credentials = get_credentials(credentials)
scope = [
'https://www.googleapis.com/auth/spreadsheets'
]
gspread_client = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_dict(credentials, scope))
try:
return gspread_client.open_by_key(doc_id).worksheet(tab_id)
except gspread.exceptions.SpreadsheetNotFound as e:
raise Exception("Trying to open non-existent or inaccessible spreadsheet document.")
except gspread.exceptions.WorksheetNotFound as e:
raise Exception("Trying to open non-existent sheet. Verify that the sheet name exists (%s)." % tab_id)
except gspread.exceptions.APIError as e:
if hasattr(e, 'response'):
error_json = e.response.json()
print(error_json)
error_status = error_json.get("error", {}).get("status")
email = credentials.get("client_email", "(email missing)")
if error_status == 'PERMISSION_DENIED':
error_message = error_json.get("error", {}).get("message", "")
raise Exception("Access was denied with the following error: %s. Have you enabled the Sheets API? Have you shared the spreadsheet with %s?" % (error_message, email))
if error_status == 'NOT_FOUND':
raise Exception("Trying to open non-existent spreadsheet document. Verify the document id exists (%s)." % doc_id)
raise Exception("The Google API returned an error: %s" % e)
示例7: get_repo_request_rows
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def get_repo_request_rows():
from oauth2client.service_account import ServiceAccountCredentials
# this file inspired by https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html
# use creds to create a client to interact with the Google Drive API
scopes = ['https://spreadsheets.google.com/feeds']
json_creds = os.getenv("GOOGLE_SHEETS_CREDS_JSON")
creds_dict = json.loads(json_creds)
# hack to get around ugly new line escaping issues
# this works for me, but later found links to what might be cleaner solutions:
# use ast.literal_eval? https://github.com/googleapis/google-api-go-client/issues/185#issuecomment-422732250
# or maybe dumping like this might fix it? https://coreyward.svbtle.com/how-to-send-a-multiline-file-to-heroku-config
creds_dict["private_key"] = creds_dict["private_key"].replace("\\\\n", "\n")
# now continue
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scopes)
client = gspread.authorize(creds)
# Find a workbook by url
spreadsheet = client.open_by_url("https://docs.google.com/spreadsheets/d/1RcQuetbKVYRRf0GhGZQi38okY8gT1cPUs6l3RM94yQo/edit#gid=704459328")
sheet = spreadsheet.sheet1
# Extract and print all of the values
rows = sheet.get_all_values()
print(rows[0:1])
return rows
示例8: _credentials
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def _credentials(self):
if not self.credentials_obj:
if self.credentials_dict:
self.credentials_obj = (
ServiceAccountCredentials.from_json_keyfile_dict(
self.credentials_dict))
else:
self.credentials_obj = (
GoogleCredentials.get_application_default())
return self.credentials_obj
示例9: __init__
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def __init__(self, path_to_secret=None, from_env=False):
if from_env:
config_dict = self._build_keyfile_dict()
self.credentials = ServiceAccountCredentials.from_json_keyfile_dict(config_dict, self.scopes)
else:
self.path_to_secret = path_to_secret
if self.path_to_secret is None:
self.credentials = None
else:
self.credentials = ServiceAccountCredentials.from_json_keyfile_name(self.path_to_secret, self.scopes)
示例10: get_credentials
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def get_credentials(self):
"""
Build GSuite credentials
"""
if settings.GSUITE_CREDENTIALS is None:
raise ImproperlyConfigured("Missing GSuite credentials")
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
settings.GSUITE_CREDENTIALS, scopes
)
return credentials.create_delegated(settings.GSUITE_DELEGATED_ACCOUNT)
示例11: __init__
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def __init__(self, credentials_dict):
"""
Build GCE service account credentials from info stored in environment variables, then build a GCE API wrapper
with those credentials. Only one of the two environment variables must be set.
:param creds_env_var_name: JSON string that contains your GCE service account credentials
:param creds_path_env_var_name: string that contains the path to the file containing your GCE service account
credentials.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
credentials_dict, scopes='https://www.googleapis.com/auth/cloud-platform')
self.compute = discovery.build('compute', 'v1', credentials=credentials)
self.deployment_manager = discovery.build('deploymentmanager', 'v2', credentials=credentials)
self.project_id = credentials_dict['project_id']
示例12: _get_application_default_credential_from_file
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def _get_application_default_credential_from_file(filename):
"""Build the Application Default Credentials from file."""
# read the credentials from the file
with open(filename) as file_obj:
client_credentials = json.load(file_obj)
credentials_type = client_credentials.get('type')
if credentials_type == AUTHORIZED_USER:
required_fields = set(['client_id', 'client_secret', 'refresh_token'])
elif credentials_type == SERVICE_ACCOUNT:
required_fields = set(['client_id', 'client_email', 'private_key_id',
'private_key'])
else:
raise ApplicationDefaultCredentialsError(
"'type' field should be defined (and have one of the '" +
AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")
missing_fields = required_fields.difference(client_credentials.keys())
if missing_fields:
_raise_exception_for_missing_fields(missing_fields)
if client_credentials['type'] == AUTHORIZED_USER:
return GoogleCredentials(
access_token=None,
client_id=client_credentials['client_id'],
client_secret=client_credentials['client_secret'],
refresh_token=client_credentials['refresh_token'],
token_expiry=None,
token_uri=GOOGLE_TOKEN_URI,
user_agent='Python client library')
else: # client_credentials['type'] == SERVICE_ACCOUNT
from oauth2client.service_account import ServiceAccountCredentials
return ServiceAccountCredentials.from_json_keyfile_dict(
client_credentials)
示例13: get_gcloud
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def get_gcloud(ctx, version: str= 'v1'):
"""
Get a configured Google Compute API Client instance.
Note that the Google API Client is not threadsafe. Cache the instance locally
if you want to avoid OAuth overhead between calls.
Parameters
----------
version
Compute API version
"""
SCOPES = 'https://www.googleapis.com/auth/compute'
credentials = None
if ctx.config.get('gcloud_credentials_file'):
credentials = ServiceAccountCredentials.from_json_keyfile_name(
ctx.config.get('gcloud_credentials_file'),
scopes=SCOPES)
if ctx.config.get('google_application_credentials'):
keyfile = json.loads(ctx.config.get('google_application_credentials'))
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
keyfile, scopes=SCOPES)
if not credentials:
credentials = GoogleCredentials.get_application_default()
if not credentials:
raise RuntimeError("Auth for Google Cloud was not configured")
compute = discovery.build(
'compute',
version,
credentials=credentials,
# https://github.com/google/google-api-python-client/issues/299#issuecomment-268915510
cache_discovery=False
)
return compute
示例14: google_api_credentials
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def google_api_credentials(scope):
"""Returns an OAuth2 credentials object for the given scope."""
if credential_info is None:
raise Exception("google service account credentials not defined in configuration")
if scope is None:
scope = ['https://www.googleapis.com/auth/drive']
if type(scope) is not list:
scope = [scope]
return ServiceAccountCredentials.from_json_keyfile_dict(credential_info, scope)
示例15: read_sheet
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_dict [as 别名]
def read_sheet(sheet_name, worksheet_index=0):
creds = ServiceAccountCredentials.from_json_keyfile_dict(credential_info, scope)
client = gspread.authorize(creds)
sheet = client.open(sheet_name).get_worksheet(worksheet_index)
return sheet.get_all_records()