首页 > 解决方案 > Python 3 - Google Drive API: AttributeError: 'Resource' object has no attribute 'children'

问题描述

I made a command-line folder selector. I want it to list all files in the folder. I've tried by using the service.children()-thing but I can't get that to work. The thing that doesn't work:

files = service.children().list(folderId=file_id).execute()

Here is the code instancing service object:

service = build('drive', 'v3', http=creds.authorize(Http()))

Other parts of the code works, so I know that the service is working

I know that the variable file_id is a valid folder. Someone who knows that it might be?

标签: pythongoogle-apigoogle-drive-apigoogle-api-python-client

解决方案


看来您最近将 API 版本从 2 升级到了 3!根据Drive API changelogchildren()不再有资源。我怀疑还有其他您没有预料到的更改,因此请务必查看该更改日志。

通过Drive V3的 Python 客户端库文档提供的一些有用信息:

about()返回关于资源。
changes()返回更改资源。
channels()返回频道资源。
comments()返回评论资源。
files()返回文件资源。
permissions()返回权限资源。
replies()返回回复资源。
revisions()返回修订资源。
teamdrives()返回 teamdrives 资源。根据发现文档
new_batch_http_request()创建对象。BatchHttpRequest

如果不想迁移,Drive V2children()还是有资源的:

about()返回关于资源。
apps()返回应用程序资源。
changes()返回更改资源。
channels()返回频道资源。
children()返回子资源。
comments()返回评论资源。
files()返回文件资源。
parents()返回父资源。
permissions()返回权限资源。
properties()返回属性资源。
realtime()返回实时资源。
replies()返回回复资源。
revisions()返回修订资源。
teamdrives()返回 teamdrives 资源。根据发现文档
new_batch_http_request()创建对象。BatchHttpRequest

那么,您的解决方案是构建 Drive REST API 的 V2 版本:

service = build('drive', 'v2', ...)

或继续使用v3并更新您的代码以使用files()现在需要的资源。

您可以使用正确的参数请求具有 id 的文件夹的子级folderId并调用listand list_next

Python3代码:

kwargs = {
  "q": "'{}' in parents".format(folderId),
  # Specify what you want in the response as a best practice. This string
  # will only get the files' ids, names, and the ids of any folders that they are in
  "fields": "nextPageToken,incompleteSearch,files(id,parents,name)",
  # Add any other arguments to pass to list()
}
request = service.files().list(**kwargs)
while request is not None:
  response = request.execute()
  # Do stuff with response['files']
  request = service.files().list_next(request, response)

参考:


推荐阅读