本文介绍了如何使用 GoogleDrive 的 Python 快速入门循环 nextPageToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是列出所有项目和每个人的 Google 云端硬盘中的文件夹.我开始尝试确保脚本可以自己运行.我已经完整阅读了 Drive REST API 文档,并且最终找到了这段代码,也可以在这里找到.

My goal is to have a list of all of the items & folders in everyone's Google Drive. I'm starting with trying to make sure the script works on my own. I have read cover-to-cover the Drive REST API documentation, and eventually found this code, which can also be found here.

from __future__ import print_function
import httplib2
import os
import sys

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

reload(sys)
sys.setdefaultencoding('utf-8')

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Drive API.

    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    results = service.files().list(
        pageSize=1000,fields="nextPageToken, files(mimeType, name)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print('{0} ({1})'.format(item['name'], item['mimeType']))

if __name__ == '__main__':
    main()

我的问题在于 nextPageToken,以及如何正确使用它.最大 PageSize 为 1000,所以我必须遍历 nextPageToken,从生成的 JSON 中获取它,将其放回原始循环(第 66 行?),以获取另外 1000 个结果.我该怎么做?

My problem is with the nextPageToken, and how to properly use it. The max PageSize is 1000, so I must loop over the nextPageToken, fetch it from the resulting JSON, put it back into the original loop (line 66?), to get another 1000 results. How do I do this?

推荐答案

让我们看看 文件:list方法

在您询问nextPageToken 的请求字段中,结果将包含nextPage 的令牌(如果nextPage 存在).结果将是这样的:

In the fields of your request you are asking the nextPageToken, the result will contain the token for the nextPage (if the nextPage exists).The result will be something like this :

{
 ...,
 "nextPageToken": "V1*3|0|XXXXXX",
 "files": [
  {
   ...
  },...
  ]
}

你可以像这样提取 nextPageToken 值:

you can extract nextPageToken value like :

token = results.get('nextPageToken', None)

List方法可以带字符串参数pageToken:

The List method can take the string parameter pageToken :

在下一页继续上一个列表请求的令牌.这应该设置为上一个中的nextPageToken"的值回应.

只需在下一个请求中设置参数pageToken即可获取下一页结果:

Just set the parameter pageToken in the next request to get the next page of results :

    results = service.files().list(
        pageSize=1000,
        pageToken=token,
        fields="nextPageToken, files(mimeType, name)").execute()
    items = results.get('files', [])

现在您可以轻松地创建一个循环来获取所有结果.

Now you can easily make a loop to get all result.

这篇关于如何使用 GoogleDrive 的 Python 快速入门循环 nextPageToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:46