Google Drive API v3 更改文件权限并获取可公开共享的链接 (Python)

问题描述 投票:0回答:4

我正在尝试使用 Google Drive API v3 和 Python 3 自动上传文件,使它们“公开”并获得一个可共享的链接,任何人,无论是否登录 Google 帐户,都可以查看和下载(但不能修改) ).

我很接近,但不太明白!观察我的代码。它需要一个名为“testing.txt”的文本文件与脚本位于同一目录中:

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

from apiclient.http import MediaFileUpload
from apiclient import errors

# https://developers.google.com/drive/api/v2/about-auth#requesting_full_drive_scope_during_app_development
SCOPES = 'https://www.googleapis.com/auth/drive' # https://stackoverflow.com/a/32309750

# https://developers.google.com/drive/api/v2/reference/permissions/update
def update_permission(service, file_id, permission_id, new_role, type):
  """Update a permission's role.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to update permission for.
    permission_id: ID of the permission to update.
    new_role: The value 'owner', 'writer' or 'reader'.

  Returns:
    The updated permission if successful, None otherwise.
  """
  try:
    # First retrieve the permission from the API.
    permission = service.permissions().get(fileId=file_id, permissionId=permission_id).execute()
    permission['role'] = new_role
    permission['type'] = type
    return service.permissions().update(fileId=file_id, permissionId=permission_id, body=permission).execute()
  except errors.HttpError as error:
    print('An error occurred:', error)
  return None

if __name__ == '__main__':
    # credential things
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    drive_service = build('drive', 'v3', http=creds.authorize(Http()))

    # create and upload file
    file_metadata = {'name': 'testing.txt'}
    media = MediaFileUpload('testing.txt',
                            mimetype='text/txt')
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id, webViewLink, permissions').execute()

    # get information needed to update permissions
    file_id = file['id']
    permission_id = file['permissions'][0]['id']

    print(file_id)
    print(permission_id)

    # update permissions?  It doesn't work!
    update_permission(drive_service, file_id, permission_id, 'reader', 'anyone') # https://stackoverflow.com/a/11669565

    print(file.get('webViewLink'))

当我运行此代码时,我收到以下信息:

1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH
01486072639937946874
An error occurred: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH/permissions/01486072639937946874?alt=json returned "The resource body includes fields which are not directly writable.">
https://drive.google.com/file/d/1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH/view?usp=drivesdk

当我将最终链接复制并粘贴到另一个浏览器中时,它不可用,因此显然它没有成功更改文件权限。但我不明白为什么它失败了。它提到了

The resource body includes fields which are not directly writable
,但我不知道这意味着什么。

有人可以帮我理解我做错了什么以及我需要改变什么来解决它吗?谢谢。

python python-3.x permissions google-drive-api
4个回答
6
投票

所选的答案不够精确(没有关于类型值和角色的信息),所以我不得不多读一点文档,这是一个工作示例,您只需要提供 file_id:

def set_permission(service, file_id):
    print(file_id)
    try:
        permission = {'type': 'anyone',
                      'value': 'anyone',
                      'role': 'reader'}
        return service.permissions().create(fileId=file_id,body=permission).execute()
    except errors.HttpError as error:
        return print('Error while setting permission:', error)

1
投票

我认为您已经能够上传文件了。所以我想建议修改一下

update_permission()
的功能。

修改点:

  • 我认为在你的情况下,需要通过创建来添加权限。
    • 所以你可以使用
      service.permissions().create()
    • 当您想要更新已创建的权限时,请使用创建权限时检索到的id。

修改后的脚本:

请修改

update_permission()
如下。

来自:

try:
  # First retrieve the permission from the API.
  permission = service.permissions().get(fileId=file_id, permissionId=permission_id).execute()
  permission['role'] = new_role
  permission['type'] = type
  return service.permissions().update(fileId=file_id, permissionId=permission_id, body=permission).execute()
except errors.HttpError as error:
  print('An error occurred:', error)
return None

致:

try:
  permission = {
      "role": new_role,
      "type": types,
  }
  return service.permissions().create(fileId=file_id, body=permission).execute()
except errors.HttpError as error:
  print('An error occurred:', error)
return None

注:

  • 此修改后的脚本假设您的环境可以使用 Drive API。

参考:


1
投票

我创建了一个 python 函数来使用文件 id 共享文件,并确保设置 sendNotificationEmail=False 解决了问题:

def share_file(file_id, email):
    
    # Share with user
    new_permissions = {
    'type': 'group',
    'role': 'writer',
    'emailAddress': email
    }

    permission_response = drive_service.permissions().create( 
        fileId=file_id, 
        body=new_permissions, 
        sendNotificationEmail=False
   ).execute()

0
投票

打字错误:请注意,在初始代码中,它在 update_permission 的函数头中显示“type”,但在更正后的代码片段中,回复使用“types”。

© www.soinside.com 2019 - 2024. All rights reserved.