繁体   English   中英

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

[英]Google Drive API v3 Change File Permissions and Get Publicly Shareable Link (Python)

我正在尝试使用带有 Python 3 的 Google Drive API v3 自动上传文件,将它们设为“公开”并获取任何人(无论是否登录 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 ,但我不知道这是什么意思。

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

这个改装怎么样? 我认为您已经能够上传文件。 所以我想提出关于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。

参考:

如果我误解了你的问题,我很抱歉。

选择的答案不够精确(与类型值和角色无关),所以我不得不多读一点文档,这是一个工作示例,您只需要提供 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)

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

我创建了一个 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM