代码之家  ›  专栏  ›  技术社区  ›  Brad Solomon

Google Drive API:检查文件夹是否存在

  •  0
  • Brad Solomon  · 技术社区  · 7 年前

    具体内容:

    • Python客户端: googleapiclient

    给定封闭驱动器ID abcdef ,文件夹名是否为 June 2019 application/vnd.google-apps.folder )存在吗?

    当前路线:

    >>> from googleapiclient.discovery import build
    >>> # ... build credentials
    >>> driveservice = build("drive", "v3", credentials=cred).files()
    >>> [i for i in driveservice.list().execute()['files'] if 
    ...  i['name'] == 'June 2019' and i['mimeType'] == 'application/vnd.google-apps.folder']                                                                                                                                                                     
    [{'kind': 'drive#file',
      'id': '1P1k5c2...........',
      'name': 'June 2019',
      'mimeType': 'application/vnd.google-apps.folder'}]
    

    所以答案是肯定的,文件夹存在。但应该有更有效的方法 via .list() driveId

    >>> FOLDER_ID = "abcdef........"
    >>> driveservice.list(corpora="drive", driveId=FOLDER_ID).execute()                                                                                                                                                                                                          
    # 403 response, even when adding the additional requested params
    

    我如何使用 q 按文件夹名查询参数?

    0 回复  |  直到 7 年前
        1
  •  4
  •   Cvetan Mihaylov    7 年前

    使用时 driveId corpora="drive" includeItemsFromAllDrives supportsAllDrives

    代码:

    response = driveservice.list(
        q="name='June 2019' and mimeType='application/vnd.google-apps.folder'",
        driveId='abcdef',
        corpora='drive',
        includeItemsFromAllDrives=True,
        supportsAllDrives=True
    ).execute()
    
    for item in response.get('files', []):
        # process found item
    

    更新:

    如果这是一个驱动器id,您确定它存在,并且您一直收到“Shared drive not found”错误,那么这可能是您为api获取的凭据的作用域问题。 另外根据这些Google API文档,似乎发生了很多变化和抨击,都与共享驱动器API支持有关。 https://developers.google.com/drive/api/v3/enable-shareddrives https://developers.google.com/drive/api/v3/reference/files/list

    如果您一直有这些问题,这里有一个替代的解决方案供您使用 spaces

    response = driveservice.list(
        q="name='June 2019' and mimeType='application/vnd.google-apps.folder'",
        spaces='drive'
    ).execute()
    
    for item in response.get('files', []):
        # process matched item
    
    推荐文章