如何向服务帐户创建的Google电子表格授予权限?

2024-03-25

我通过以下步骤创建了一个 Google 服务帐户:

  1. 打开这个链接:https://console.cloud.google.com/apis/credentials?project=MyProject https://console.cloud.google.com/apis/credentials?project=MyProject
  2. 点击创建凭证按钮,然后选择服务帐号
  3. Fill the Service account details field like this. And then CREATE AND CONTINUE enter image description here
  4. On the 授予此服务帐户对项目的访问权限, click +添加角色,然后我选择快速访问 -> 基本 -> 所有者, then CONTINUE
  1. On the 授予用户对此服务帐户的访问权限,我用我平常的电子邮件地址填写它。然后单击DONE button.

现在我的服务帐户列表中有这样的内容:

  1. 单击服务帐户,然后转到权限选项卡,然后单击授予访问权限 button:
  1. 添加主体使用我的电子邮件地址,并将角色设置为服务帐户管理员, then SAVE.
  1. 现在点击KEYS选项卡,然后单击ADD KEY下拉菜单,然后选择创建新密钥
  1. CREATE关键是JSON type.

  2. 下载 JSON 文件后,我将其放在我的代码路径中。我运行的代码是来自 Google Spreadsheet API 文档的代码,用于创建新的电子表格,以下是代码片段:



    def create(title):
        creds = service_account.Credentials.from_service_account_file('odoo-spreadsheet-371808-7186d4c03b4c.json',
                                                                      scopes=SCOPES)
        service = build('sheets', 'v4', credentials=creds)
        spreadsheet = {
            'properties': {
                'title': title
            },
        }
        spreadsheet = service.spreadsheets().create(body=spreadsheet)
        response = spreadsheet.execute()
        print('response', response)
        print('spreadsheetId:', response.get('spreadsheetId'))
        print('spreadsheetUrl:', response.get('spreadsheetUrl'))
  

代码成功运行,并在我上面创建的服务帐户上创建了一个新的电子表格,但是当我使用我已被授予的电子邮件在浏览器上打开电子表格Url(如上面的步骤 5 和 7)时,我的访问被拒绝,我看到这样的屏幕,这意味着我无权访问电子表格。

我不是已经在服务帐户上授予了电子邮件访问权限(如上面的步骤 5 和 7)吗?那么为什么我的电子邮件仍然无权访问由我的服务帐户创建的电子表格?


我使用以下代码片段向创建的电子表格授予我的电子邮件权限:

def update_spreadsheet_permission(drive_service, spreadsheet_id, type, role, email_address):
    new_file_permission = {
        'type': type,
        'role': role,
        'emailAddress': email_address,
    }

    permission_response = drive_service.permissions().create(
        fileId=spreadsheet_id, body=new_file_permission).execute()

    return permission_response

到目前为止,代码可以向电子邮件授予权限role read and write。但代码无法更改电子表格type to owner yet.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向服务帐户创建的Google电子表格授予权限? 的相关文章

随机推荐