更新文件上的python google api v3错误

2024-10-02 06:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用python中的GoogleDriveAPIv3,使用google官方指令中的代码更新GoogleDrive上的文件

但我收到一个错误:

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


Tags: the代码inapiidnewpdfservice
1条回答
网友
1楼 · 发布于 2024-10-02 06:30:28

问题是您使用的对象与从files.get方法返回的对象相同。File.update方法使用HTTP补丁方法,这意味着您发送的所有参数都将被更新。file.get返回的此对象包含文件对象的所有字段。当您将其发送到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'

您应该做的是创建一个新对象,然后使用这个新对象更新文件,只更新要更新的字段。记住在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()

相关问题 更多 >

    热门问题