Ric*_*ard 5 google-authentication google-sheets google-cloud-iam
我已经与我的 Google 服务帐户电子邮件共享了一个 Google 表格,它看起来像:
myappname-service@myappname-266229.iam.gserviceaccount.com
这允许我的应用程序访问该 Google 表格。
我希望能够使用别名为丑陋的自动生成的服务帐户电子邮件 ( myappname-service@myappname-266229.iam.gserviceaccount.com)的自定义电子邮件地址(例如 google@myappname.com)共享 Google 表格。
我怎么能去做这件事?
编辑:
用于与 Google API 交互的代码示例
from google_auth_httplib2 import AuthorizedHttp
from google.oauth2 import service_account
import pygsheets
def _get_gc():
scope = ['https://www.googleapis.com/auth/spreadsheets']
credentials = service_account.Credentials.from_service_account_file(
settings.GOOGLE_SERVICE_AUTH_FILE,
scopes=scope,
)
http = AuthorizedHttp(credentials, http=HTTP)
logger.info('Created GC creds, returning...')
return pygsheets.authorize(custom_credentials=credentials, http=http)
def do_something(url):
gc = _get_gc()
spreadsheet = gc.open_by_url(url)
Run Code Online (Sandbox Code Playgroud)
与常规帐户不同,服务帐户不能有别名。他们的电子邮件地址定义为:
\n您不能给它额外的别名。
\n如果您想避免与自动生成的服务帐户电子邮件地址共享 Google 表格,但希望继续使用服务帐户与 API 交互,则最好的选择是与具有可接受电子邮件地址的常规帐户共享表格地址,并使用服务帐户来模拟此常规帐户,并在与 API 交互时
\n服务帐户最有用的事情之一是,您可以授予它模拟域中任何用户并代表其访问数据的能力。这称为域范围委派,可以通过以下步骤为服务帐户激活它:
\n\n重要提示:您需要成为 G Suite 域的管理员才能委派全域权限。
\n此时,您的服务帐户可以模拟该帐户中的任何用户。要实际模拟帐户,您只需在构建凭据时指定要模拟的帐户即可。
\n在您的具体情况下,您需要subject在调用时提供参数,正如您在此页面from_service_account_file的域范围委托部分中看到的那样:
credentials = service_account.Credentials.from_service_account_file(\n settings.GOOGLE_SERVICE_AUTH_FILE,\n scopes=scope,\n subject="your-account@your-domain.com"\n )\nRun Code Online (Sandbox Code Playgroud)\n