使用 Google Drive API 将文件复制到特定的父文件夹中?
问题描述
我使用的是 Python 2.7 和 服务帐号 根据标题将 Google Drive 中的文件复制到另一个文件夹中.这需要我执行五 (5!) 个命令:
I'm using Python 2.7 and a service account to copy a file in Google Drive into another folder based on its title. This requires me to execute five (5!) commands:
- 按标题查找文件 ID.(
files().list
) - 按标题查找父文件夹 ID (
files().list
) - 复制文件(
files().copy
) - 将所有权转让给真实帐户(
files().insert
) - 移入父文件夹.(
parents().insert
)
这一切都有效,但我想减少调用次数,首先这意味着缓存 ID,这样我就不必调用 files().list
.我要做的下一件事,特别是我遇到这个问题的地方,是如何在 files().copy
命令中设置父文件夹 within.该文档有一个可选的 parents
参数,描述如下:
This all works but I'd like to reduce the number of calls and first that means caching the ID's so I don't have to call files().list
. The next thing I'm trying to do, and specifically where I'm at with this question, is how to set the parent folder within the files().copy
command. The documentation has an optional parents
parameter described like so:
包含此文件的父文件夹的集合.设置此字段会将文件放入所有提供的文件夹中.插入时,如果没有提供文件夹,文件将放在默认的根文件夹中.
Collection of parent folders which contain this file. Setting this field will put the file in all of the provided folders. On insert, if no folders are provided, the file will be placed in the default root folder.
虽然它没有说,但我知道它是指父 ID,因为这是在其他地方使用的.但是,在客户端库中设置这个数组并不会产生效果:没有错误并且文件肯定不在正确的文件夹中.
Although it doesn't say, I know it means parent ID's since that's what is used everywhere else. However, setting this array in the client library doesn't produce an effect: no error and the file is definitely not in the right folder.
newfile = {'title': newtitle, 'parents' : [ parentFolderId ]}
service.files().copy(fileId=originalId, body=newfile).execute()
有没有人有运气有这个一个>?我还缺少什么吗?
Has anyone had any luck with this? Is there something else I'm missing?
奖励:在复制命令中转移所有权?也许我的服务帐户可以冒充我?
Bonus: transfer ownership in copy command? Perhaps my service account could impersonate me?
解决方案
啊哈!parents
数组是具有 id
字段的对象列表:
Ah ha! The parents
array is a list of objects with the id
field:
newfile = {'title': newtitle, 'parents' : [ { "id" : parentFolderId } ]}
service.files().copy(fileId=originalId, body=newfile).execute()
如果/当我弄清楚如何设置权限时,我会更新这个.
I'll update this if/when I figure out how to set permissions also.
这里有个奇怪的提示是文件仍然被复制到驱动器根目录以及我指定的父文件夹.
One strange note here is that the file is still being copied to the drive root as well as the parent folder(s) I specify.
相关文章