簡體   English   中英

如何使用google drive api獲取google drive中所有文件的名稱?

[英]How to fetch name of all files in google drive using google drive api?

我正在嘗試獲取 google 驅動器中所有文件的名稱,但問題是我只能獲取特定數量的文件,如何刪除此限制並獲取所有文件,這是 google 在其網站上提供的代碼

我正在使用谷歌驅動器 API v3

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()

在這段代碼中有一個變量 pageSize ,它的值是 10,如果我增加它的值,這樣我就可以獲取更多文件,但我想獲取所有文件,所以我該怎么做。

Files.list有一個名為 pagesize 的可選參數

pageSize integer 每頁返回的最大文件數。 即使在到達文件列表末尾之前,部分或空的結果頁面也是可能的。 可接受的值為 1 到 1000,包括 1 到 1000。 (默認值:100)

您已將您的 pageSize=10 設置為 1000,然后使用 nextPageToken 選擇下一組行(如果有更多行)。

我不是 python 開發人員,以下代碼是猜測。

page_token = saved_start_page_token;
while page_token is not None:
    response = service.changes().list(pageToken=page_token,
    pageSize=1000, fields="nextPageToken, files(id, name)").execute()
    page_token = response.get('nextPageToken')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM