从共享文件夹中获取文件

时间:2018-04-25 20:08:04

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

我想从共享文件夹中访问文件,然后下载它们。问题是我最终只能得到一个"入门"文件,我不知道如何解决这个问题。我尝试了几件事,包括在files()下进行查询。获取函数但没有成功。这是我的代码:

from google.oauth2 import service_account
import googleapiclient.discovery
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http


scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('server_secret.json', scopes)

http_auth = credentials.authorize(Http())
service = build('drive', 'v3', http=http_auth)

results = service.files().list(
    pageSize=10, fields="nextPageToken, files(id, name)").execute()

files = results.get('files', [])

for f in files:
    print(f)

2 个答案:

答案 0 :(得分:0)

假设您引用的文件夹具有唯一名称,您可以尝试以下内容:

def get_folder(name):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)
    results = service.files().list(
        pageSize=10,
        q=("name = '{0}'".format(name) +
           " and mimeType = 'application/vnd.google-apps.folder'"),
        corpora="user",
        fields="nextPageToken, files(id, name, webContentLink, " +
               "createdTime, modifiedTime)").execute()
    items = results.get('files', [])
    if not items:
        return None
    return items[0]

此函数指定与Drive文件夹对应的mime类型,并返回与给定名称匹配的第一个结果。如果您的文件夹名称不唯一,则可以修改它以返回每个匹配的结果。

def get_folder_contents(folder_id):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    results = service.files().list(
        q=("'{0}' in parents".format(folder_id)),
        corpora="user",
        fields="nextPageToken, files(id, name, webContentLink, " +
               "createdTime, modifiedTime)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    return items

了解云端硬盘文件夹的id后,您可以在id中查询parents项中的所有项目。 有了这两个函数,您就可以执行以下操作:

folder = get_folder('my_folder_name')
folder_items = get_folder_contents(folder['id'])

for item in folder_items:
    # decide if you should download
    my_download_function(url=item['webContentLink'])

答案 1 :(得分:0)

File.list有一个名为q的参数,它允许你search。搜索“sharedWithMe”将返回与其他用户共享的所有内容。

  

sharedWithMe boolean =,!=用户的“与我共享”集合中的文件。

def get_folder(name):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)
    results = service.files().list(
        pageSize=10,
        q=("sharedWithMe"),
        corpora="user",
        fields="*").execute()
    items = results.get('files', [])
    if not items:
        return None
    return items[0]

这将为您提供与您分享的所有内容。

如果您知道要查找的内容的名称,也可以添加。

  

sharedWithMe和name包含'hello'