python google api v3 更新文件错误

python google api v3 Error on update file

我尝试在 python 中使用 google 驱动器 api v3 以使用官方 google 指令中的代码更新 google 驱动器上的文件。

但是我收到一个错误:

The resource body includes fields which are not directly writable.

如何解决?

这是我尝试使用的代码:

  try:
      # First retrieve the file from the API.

       file = service.files().get(fileId='id_file_in_google_drive').execute()
       # File's new metadata.
       file['title'] = 'new_title'
       file['description'] = 'new_description'
       file['mimeType'] = 'application/pdf'

       # File's new content.
       media_body = MediaFileUpload(
               '/home/my_file.pdf',
                mimetype='application/pdf',
                resumable=True)

       # Send the request to the API.
       updated_file = service.files().update(
                fileId='id_file_in_google_drive',
                body=file,
                media_body=media_body).execute()
            return updated_file
        
  except errors:
       print('An error occurred: %s')
       return None

问题是您使用的 object 与从 files.get 方法返回的相同。 File.update 方法使用 HTTP PATCH 方法,这意味着您发送的所有参数都将被更新。 file.get 返回的 object 包含文件 object 的所有字段。当您将它发送到 file.update 方法时,您正在尝试更新许多不可更新的字段。

   file = service.files().get(fileId='id_file_in_google_drive').execute()
   # File's new metadata.
   file['title'] = 'new_title'
   file['description'] = 'new_description'
   file['mimeType'] = 'application/pdf'

您应该做的是创建一个新的 object,然后使用这个新的 object 更新文件,仅更新您要更新的字段。请记住在 Google Drive v3 中它的名称不是标题。

file_metadata = {'name': 'new_title' , 'description': 'new description'}

updated_file = service.files().update(
            fileId='id_file_in_google_drive',
            body=file_metadata ,
            media_body=media_body).execute()