没有在Drive API请求中列出任何Google Drive文件

5
我正在尝试使用桌面应用程序获取我的Google Drive中文件列表的方法。代码如下:
def main(argv):

    storage = Storage('drive.dat')
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run(FLOW, storage)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build("drive", "v2", http=http)
    retrieve_all_files(service)

然后在retrieve_all_files函数中,我打印出了文件:
param = {}
if page_token:
    param['pageToken'] = page_token
    files = service.files().list(**param).execute()
    print files

但是在我认证我的账户之后,打印的文件列表中没有任何项目。是否有人遇到类似的问题或知道解决方法?


你能贴出retrieve_all_files的全部内容吗?看起来是一个很有用的函数。 - Ali Afshar
@AliAfshar,您可以在此处找到它:https://developers.google.com/drive/v2/reference/files/list - Robin W.
2个回答

6
请纠正我如果我错了,但我认为你正在使用 https://www.googleapis.com/auth/drive.file 范围,它只返回由您的应用程序创建或已经通过Google Drive UIPicker API显式打开的文件。
要检索所有文件,您需要使用更广泛的范围: https://www.googleapis.com/auth/drive
要了解有关不同范围的更多信息,请查看文档

1
我尝试了你的建议,但返回的列表中仍然没有内容... - Robin W.
1
源代码可以在哪里获取以便我们尝试复现吗?请确保在更改范围时删除drive.dat,因为它可能使用未经批准的旧令牌进行更广泛的范围。 - Alain

0

首先,您需要通过迭代page_token来获取My Drive以及任何子文件夹的所有内容。还有一些其他可能性,比如没有提供查询等。请尝试以下操作:

def retrieve_all_files(service):
    """ RETURNS a list of files, where each file is a dictionary containing
        keys: [name, id, parents]
    """

    query = "trashed=false"

    page_token = None
    L = []

    while True:
        response = service.files().list(q=query,
                                             spaces='drive',
                                             fields='nextPageToken, files(id, name, parents)',
                                             pageToken=page_token).execute()
        for file in response.get('files', []):  # The second argument is the default
            L.append({"name":file.get('name'), "id":file.get('id'), "parents":file.get('parents')})

        page_token = response.get('nextPageToken', None)  # The second argument is the default

        if page_token is None:  # The base My Drive folder has None
            break

    return L

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接