无法与共享驱动器和文件交互| Python Google Drive API v3

Nic*_*edo 1 python python-3.x google-drive-api google-drive-shared-drive

我正在开发一个 python 脚本,该脚本将使用 Google Drive API v3 管理共享驱动器上的文件。但是,当我尝试下载或替换该文件时,出现以下错误:

An error occurred: <HttpError 404 when requesting https://www.googleapis.com/upload/drive/v3/files/1HhCxshcR17I4rM0gtBIvHzEH_jzd7nV2?alt=json&uploadType=multipart returned "File not found: 1HhCxshcR17I4rM0gtBIvHzEH_jzd7nV2.">
Run Code Online (Sandbox Code Playgroud)

这是我的代码

def update_file(service, file_id, new_title, new_description, new_mime_type,
                                new_filename):
    """Update an existing file's metadata and content.

    Args:
        service: Drive API service instance.
        file_id: ID of the file to update.
        new_title: New title for the file.
        new_description: New description for the file.
        new_mime_type: New MIME type for the file.
        new_filename: Filename of the new content to upload.
        new_revision: Whether or not to create a new revision for this file.
    Returns:
        Updated file metadata if successful, None otherwise.
    """
    try:
        # File metadata
        file_metadata = {
            'name': new_title, 
            'description': new_description
        }

        # File's new content.
        media_body = MediaFileUpload(
                new_filename, mimetype=new_mime_type) # In this case the file is small so no resumable flag needed

        # Send the request to the API.
        updated_file = service.files().update(
                fileId=file_id,
                body=file_metadata,
                media_body=media_body).execute()
        return updated_file
    except Exception as e:
        print ('An error occurred: %s' % e)
        return None

#Update an existing entry in database
def updateItem(dataIndex):
        
    userInput = input(header[2]) #Update quantity
    if userInput[0] == '+':
        ws['C' + str(dataIndex)] = str( int(ws['C' + str(dataIndex)].value) + int(userInput[1:]) )
    elif userInput[0] == '-':
        ws['C' + str(dataIndex)] = str( int(ws['C' + str(dataIndex)].value) - int(userInput[1:]) )
    else:
        ws['C' + str(dataIndex)] = str( userInput )
    
    ws['D' + str(dataIndex)] = today #Update date
    wb.save(filepath)
Run Code Online (Sandbox Code Playgroud)

如何在共享云端硬盘或文档上使用 Google Drive API?这在我个人的驾驶中效果很好。

Tan*_*ike 5

file_id如果您想在 Drive API v3 中使用共享 Drive 中的文件files().update(),可以进行以下修改吗?

修改后的脚本:

updated_file = service.files().update(
        fileId=file_id,
        body=file_metadata,
        media_body=media_body,
        supportsAllDrives=True  # <--- Added
        ).execute()
Run Code Online (Sandbox Code Playgroud)
  • supportsAllDrives的默认值为false。因此在本例中,true用于使用共享云端硬盘中的文件。

参考: