簡體   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