No Google Drive files are listed in Drive API requ

2019-04-30 01:40发布

问题:

I am trying to get a list of the files in my Google Drive using a desktop app. The code is as follows:

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)

Then in retrieve_all_files, I print the files:

param = {}
if page_token:
    param['pageToken'] = page_token
    files = service.files().list(**param).execute()
    print files

But after I authenticate to my account, the printed file list has no items. Does anyone have a similar problem or know of a solution to this?

回答1:

Please correct me if I'm wrong but I believe you are using the https://www.googleapis.com/auth/drive.file scope, which only returns files that your app has created or have been explicitly opened with your app using the Google Drive UI or the Picker API.

To retrieve all files, you will need to use the broader scope: https://www.googleapis.com/auth/drive.

To learn more about the different scopes, have a look at the documentation.



回答2:

For one thing, you need to iterate through page_token in order to get all the contents of My Drive as well as any subfolders. There are a few other things it could be too like not providing a query, etc. Try this:

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