本文整理汇总了Python中oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceAccountCredentials.from_json_keyfile_name方法的具体用法?Python ServiceAccountCredentials.from_json_keyfile_name怎么用?Python ServiceAccountCredentials.from_json_keyfile_name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2client.service_account.ServiceAccountCredentials
的用法示例。
在下文中一共展示了ServiceAccountCredentials.from_json_keyfile_name方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_gsheet_client
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [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: __init__
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def __init__(self,
project_id,
service_cred_path=None,
logger=None,
metrics=None,
**options):
self.project_id = project_id
self.endpoint = ("https://fcm.googleapis.com/v1/"
"projects/{}/messages:send".format(self.project_id))
self.token = None
self.metrics = metrics
self.logger = logger or Logger()
self._options = options
if service_cred_path:
self.svc_cred = ServiceAccountCredentials.from_json_keyfile_name(
service_cred_path,
["https://www.googleapis.com/auth/firebase.messaging"])
self._sender = treq.post
示例3: get_service_object
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [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: handle
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def handle(self, *args, **options):
"""Fetch Mess Menus."""
# Use credentials to create a client to interact with the Google Drive API
print("Authorizing - ", end="", flush=True)
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_client_secret.json', scope)
client = gspread.authorize(creds)
print("OK")
# Iterate over all hostels
for hostel in Hostel.objects.all():
print("Updating " + hostel.name + " - ", end="", flush=True)
if hostel.mess_gsheet:
try:
fetch_hostel(client, hostel)
print("OK")
except Exception: # pylint: disable=W0703
print("FAIL")
else:
print("SKIP")
示例5: get_access_token
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def get_access_token(ga_key_filepath):
"""Get the access token for Google Analytics.
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.
_credentials = ServiceAccountCredentials.from_json_keyfile_name(
ga_key_filepath, SCOPE)
return _credentials.get_access_token().access_token
示例6: upload_test_results
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def upload_test_results(results, name, sheet, credentials):
"""Upload the test results to the the google sheet"""
if not sheet:
return
if not results:
print('ERROR: No results specified')
return
credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials, SCOPES)
gcloud = gspread.authorize(credentials)
spreadsheet = gcloud.open_by_url(sheet)
try:
worksheet = spreadsheet.worksheet(results["suite"])
except gspread.exceptions.WorksheetNotFound:
print(" * ERROR: Worksheet {} not found".format(results["suite"]))
return
filename = "{}_{}_{}.json".format(name, results.get('suite'), results.get('timestamp'))
gsheets_import(results, worksheet, filename)
示例7: make_access_token
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def make_access_token(secret_token_json):
"""Construct an access token from service account token."""
logging.info("Constructing an access token with scope " + _GOOGLE_API_SCOPE)
credentials = ServiceAccountCredentials.from_json_keyfile_name(
secret_token_json,
scopes=[_GOOGLE_API_SCOPE])
logging.info("Service account email: " + credentials.service_account_email)
token = credentials.get_access_token().access_token
return token
示例8: generate_jwt
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def generate_jwt(args):
"""Generates a signed JSON Web Token using a service account. Based on https://cloud.google.com/endpoints/docs/service-to-service-auth"""
# Make sure the service account has "Service Account Token Creator" permissions in Google IAM
credentials = ServiceAccountCredentials.from_json_keyfile_name(
args.service_account_file).create_scoped(['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
serviceName='iam', version='v1', credentials=credentials)
now = int(time.time())
header_json = json.dumps({
"typ": "JWT",
"alg": "RS256"})
payload_json = json.dumps({
'iat': now,
"exp": now + 3600,
'iss': args.issuer if args.issuer else credentials.service_account_email,
"target_audience": 'https://' + args.aud,
"aud": "https://www.googleapis.com/oauth2/v4/token"
})
header_and_payload = '{}.{}'.format(
base64.urlsafe_b64encode(header_json),
base64.urlsafe_b64encode(payload_json))
slist = service.projects().serviceAccounts().signBlob(
name="projects/-/serviceAccounts/" + credentials.service_account_email,
body={'bytesToSign': base64.b64encode(header_and_payload)})
res = slist.execute()
signature = base64.urlsafe_b64encode(
base64.decodestring(res['signature']))
signed_jwt = '{}.{}'.format(header_and_payload, signature)
return signed_jwt
示例9: main
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def main(args):
"""Generates a signed JSON Web Token using a Google API Service Account."""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
args.service_account_file)
now = int(time.time())
payload = {
"exp": now + credentials.MAX_TOKEN_LIFETIME_SECS,
"iat": now,
"aud": args.aud,
}
if args.email:
payload["email"] = args.email
if args.groupId:
payload["groupId"] = args.groupId
if args.issuer:
payload["iss"] = args.issuer
payload["sub"] = args.issuer
else:
payload["iss"] = credentials.service_account_email
payload["sub"] = credentials.service_account_email
signed_jwt = oauth2client.crypt.make_signed_jwt(
credentials._signer, payload, key_id=credentials._private_key_id)
return signed_jwt
示例10: _open_doc
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def _open_doc(url):
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
settings.GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH, scope)
gc = gspread.authorize(credentials)
try:
return gc.open_by_url(url)
except gspread.SpreadsheetNotFound:
raise SpreadsheetNotFound
示例11: get_service_acct_creds
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def get_service_acct_creds(key_file, verbose=False):
'''Generate service account credentials using the given key file.
key_file: path to file containing private key.
'''
### backcompatability for .p12 keyfiles
if key_file.endswith('.p12') or key_file.endswith('.pem'):
from edx2bigquery_config import auth_service_acct as SERVICE_ACCT
if verbose:
print "using key file"
print "service_acct=%s, key_file=%s" % (SERVICE_ACCT, KEY_FILE)
try:
creds = ServiceAccountCredentials.from_p12_keyfile(
SERVICE_ACCT,
key_file,
scopes=BIGQUERY_SCOPE)
except Exception as err: # fallback to old google SignedJwtAssertionCredentials call
with open (key_file, 'rb') as f:
key = f.read();
creds = SignedJwtAssertionCredentials(
SERVICE_ACCT,
key,
BIGQUERY_SCOPE)
return creds
###
creds = ServiceAccountCredentials.from_json_keyfile_name(
key_file,
BIGQUERY_SCOPE)
return creds
示例12: get_firebase_access_token
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def get_firebase_access_token(config_file_name):
"""
This returns the access token for a given JSON config file name
:param config_file_name:
:return:
"""
fbt = "firebase_token"
now = time.time()
app_store = get_app_local_store()
if fbt not in app_store or not isinstance(app_store[fbt], dict):
# initialize the firebase_token in the app_store as dict
app_store[fbt] = {}
if not isinstance(app_store[fbt].get(config_file_name), AccessToken) or \
now > app_store[fbt].get(config_file_name).expires_at:
# If the type of the config is not class AccessToken or
# if the token has expired
credentials = ServiceAccountCredentials.from_json_keyfile_name(config_file_name, SCOPES)
log.debug("Fetching a new access_token for {!r} from firebase...".format(config_file_name))
access_token_info = credentials.get_access_token()
# Now we set the expiration date for the new access_token with a margin of 10 seconds
At = AccessToken(access_token_info.access_token, access_token_info.expires_in)
# We do not use a lock here: The worst that could happen is that two threads
# fetch new auth tokens concurrently. In this case, one of them wins and is written to the dictionary.
app_store[fbt][config_file_name] = At
readable_time = datetime.datetime.fromtimestamp(At.expires_at).isoformat()
log.debug(u"Setting the expiration for {!r} of the new access_token to {!s}.".format(config_file_name, readable_time))
return app_store[fbt][config_file_name].access_token
示例13: __init__
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def __init__(self, spreadsheet_name):
self.item_col = 1
self.price_col = 2
self.frequency_col = 3
self.url_col = 4
self.product_name_col = 5
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',
scope)
client = gspread.authorize(creds)
self.sheet = client.open(spreadsheet_name).sheet1
示例14: fetch
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def fetch(self, **kwargs):
''' Fetches an email using the Gmail API users.messages.get()
method. It leverages the IsThisLegit service account to impersonate
the user in order to retrieve the email by message ID. This prevents
users from having to manually accept the OAuth permission dialog before
reporting phishing emails.
Expected kwargs:
userId - The userID who reported the email
messageId - The Gmail message ID to fetch
'''
userId = kwargs.get('userId')
messageId = kwargs.get('messageId')
scopes = ['https://www.googleapis.com/auth/gmail.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
config['gae']['service_account_key'], scopes=scopes)
delegated_credentials = credentials.create_delegated(userId)
http_auth = delegated_credentials.authorize(Http())
service = build('gmail', 'v1', http=http_auth)
response = service.users().messages().get(
userId=userId, id=messageId, format='raw').execute()
if not response or 'raw' not in response:
raise EmailFetchError('Error fetching email: User {}, thread {}'.
format(userId, messageId))
message = base64.urlsafe_b64decode(str(response['raw']))
return message
示例15: get_Auth
# 需要导入模块: from oauth2client.service_account import ServiceAccountCredentials [as 别名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 别名]
def get_Auth():
credentials = ServiceAccountCredentials.from_json_keyfile_name(cfg.CREDENTIAL_SERVICE, cfg.DEFAULT_SCOPES)
http = httplib2.Http(memcache, timeout=60)
#http = httplib2.Http()
return credentials.authorize(http)