gpt4 book ai didi

python - 如何获取用于调用 google api 的委托(delegate)凭证对象?

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:16 26 4
gpt4 key购买 nike

我正在尝试通过 API 获取 gsuite 警报。我已经根据他们的 docs 创建了一个服务帐户我已将该服务帐户分配给我的谷歌云功能。

我不想使用环境变量或将凭据与源代码一起上传,但我想利用函数使用的默认服务帐户。

from googleapiclient.discovery import build

def get_credentials():

# if one knows credentials file location(when one uploads the json credentials file or specify them in environment variable) one can easily get the credentials by specify the path.
# In case of google cloud functions atleast I couldn't find it the path as the GOOGLE_APPLICATION_CREDENTIALS is empty in python runtime

# the below code work find if one uncomments the below line
#credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location)

credentials = < how to get default credentials object for default service account?>

delegated_credentials = credentials.create_delegated('admin@alertcenter1.bigr.name').create_scoped(SCOPES)
return delegated_credentials

def get_alerts(api_name, api_version, key_file_location=None):

delegated_credentials = get_credentials()
alertcli = build(api_name, api_version, credentials=delegated_credentials)
resp = alertcli.alerts().list(pageToken=None).execute()
print(resp)


有什么方法可以创建默认凭据对象。我试过使用from google.auth import credentials 但这不包含 create_delegated 函数和我也尝试过 ServiceAccountCredentials() 但这需要签名者。

最佳答案

这是一个使用 Gmail API 和委托(delegate)凭据的示例。服务帐户凭据需要启用“启用 G Suite 全域委派”。

from google.oauth2 import service_account
from googleapiclient.discovery import build

credentials = service_account.Credentials.from_service_account_file(
credentials_file,
scopes=['https://www.googleapis.com/auth/gmail.send'])

impersonate = 'username@example.com'

credentials = credentials.with_subject(impersonate)

service = build('gmail', 'v1', credentials=credentials)

关于python - 如何获取用于调用 google api 的委托(delegate)凭证对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55356089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com