dmi*_*one 1 python google-api google-drive-api google-api-python-client
我尝试在 python 中使用 googledrive api v3 来使用官方 google 指令中的代码更新 googledrive 上的文件。
但我收到一个错误:
资源主体包括不可直接写入的字段。
怎么解决呢?
这是我尝试使用的代码:
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
Run Code Online (Sandbox Code Playgroud)
问题是您使用的对象与从 files.get 方法返回的对象相同。File.update 方法使用 HTTP PATCH 方法,这意味着您发送的所有参数都将被更新。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'
Run Code Online (Sandbox Code Playgroud)
您应该做的是创建一个新对象,然后使用这个新对象更新文件,仅更新您想要更新的字段。请记住在 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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
518 次 |
最近记录: |