0

我正在使用 Google 服务帐户使用 Resumable Method 将视频上传到 Google Drive。python 代码运行良好,但我遇到了 Google 服务帐户存储问题。

Google 服务帐户似乎只能有 15 GB 的存储空间。即使我将视频上传到常规的 Google Drive 文件夹,该视频仍归服务帐户所有。因此,我尝试将视频的所有者转移到其他帐户,但没有成功,错误是bad request. User message: \"You can't yet change the owner of this item. (We're working on it.)

下面是我的 python 代码,它从服务帐户生成访问令牌并执行可恢复上传

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'creds.json',
        scopes='https://www.googleapis.com/auth/drive'
    )

    delegated_credentials = credentials.create_delegated('service_account_email')

    access_token = delegated_credentials.get_access_token().access_token
    
    filesize = os.path.getsize(file_location)

    # Retrieve session for resumable upload.

    headers1 = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"}
    params = {
        "name": file_name,
        "mimeType": "video/mp4",
        "parents": [folder_id]
    }
    r = requests.post(
        "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
        headers=headers1,
        data=json.dumps(params)
    )

    location = r.headers['Location']

    # Upload the file.

    headers2 = {"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)}
    r = requests.put(
        location,
        headers=headers2,
        data=open(file_location, 'rb')
    )

是否有解决方法或增加 Google 服务帐户的存储限制?

任何建议将不胜感激。谢谢!

4

1 回答 1

0
  • 您想使用服务帐户进行可恢复上传到云端硬盘。
  • 您希望视频的所有者不是服务帐户,而是具有足够云端硬盘存储容量的普通帐户。

如果这是正确的,那么您只需将域范围的权限委派给服务帐户,以便它可以代表域中的任何用户行事,并且在上传文件时,模拟您想要成为所有者的帐户文件。

委派域范围的权限:

这里解释了授予域范围权限的过程:

  • 服务帐户页面上,选择您的服务帐户,并在编辑 SA 时单击,然后SHOW DOMAIN-WIDE DELEGATION在刚刚显示的内容上,选中启用 G Suite 域范围委派选项。
  • 完成此操作后,转到管理控制台,然后转到Main menu > Security > API Controls
  • 域范围委派窗格中选择管理域范围委派,然后单击添加新的
  • 填写相应字段:(1) 在Client ID中,输入 SA 的Client ID,您可以在凭证 JSON 文件和 Service Account 页面中找到它,以及 (2) 在OAuth scopes中,添加与您希望 SA 代表域中的用户访问的资源。在这种情况下,我想这只是https://www.googleapis.com/auth/drive.
  • 单击Authorize后,您已授予服务帐户代表域中任何用户访问资源的能力。

冒充其他用户:

现在服务帐户模拟域中的任何用户,但您必须指定您希望它模拟的用户。为此,您只需对代码进行一些小改动。现在,您正在通过以下方式设置service_account_email委托凭据时create_delegated

delegated_credentials = credentials.create_delegated('service_account_email')

也就是说,服务帐户代表服务帐户行事。如果您不想冒充另一个帐户,则不需要这行代码(它没有任何效果,因为credentials两者delegated_credentials都引用同一个帐户(服务帐户)。

但是由于您想使用服务帐户代表另一个帐户行事,因此您必须在此行中指定此其他帐户的电子邮件地址:

delegated_credentials = credentials.create_delegated('user_account_email')

这是您需要对代码进行的唯一更改。如果您已授予域范围的委派,则服务帐户将像其他用户一样行事。就像是这个其他用户上传了文件一样,所以这个用户将是文件的所有者。

笔记:

  • 您正在使用已弃用的库( oauth2client)。由于这仍然有效,因此现在没有真正需要这样做,但请考虑将您的代码更改为google-auth

参考:

于 2020-06-26T10:23:30.670 回答