【问题标题】:No Google Drive files are listed in Drive API requestDrive API 请求中未列出任何 Google Drive 文件
【发布时间】:2023-03-06 20:15:02
【问题描述】:

我正在尝试使用桌面应用程序获取我的 Google 云端硬盘中的文件列表。代码如下:

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

但是在我对我的帐户进行身份验证后,打印的文件列表没有任何项目。有没有人有类似的问题或知道解决方案?

【问题讨论】:

标签: python google-drive-api google-api-python-client


【解决方案1】:

如果我错了,请纠正我,但我相信您使用的是 https://www.googleapis.com/auth/drive.file 范围,它只返回您的应用创建的文件或使用 Google Drive UIPicker API 使用您的应用显式打开的文件.

要检索所有文件,您需要使用更广泛的范围:https://www.googleapis.com/auth/drive

要了解有关不同范围的更多信息,请查看documentation

【讨论】:

  • 我已经尝试了你的建议,但返回列表中仍然没有内容...
  • 源代码是否在任何地方都可用,以便我们可以尝试复制?请确保在更改范围时删除 drive.dat,因为它可能使用未经批准用于更广泛范围的旧令牌。
【解决方案2】:

一方面,您需要遍历 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

【讨论】:

    猜你喜欢
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多