使用 Google Drive 获取 WebViewLinks

Getting WebViewLinks with Google Drive

我刚开始尝试使用 Google 驱动器 API。使用快速入门指南,我设置了身份验证,我可以打印我的文件列表,甚至可以复印。一切都很好,但是我在尝试从 Drive 上的文件访问数据时遇到了问题。特别是,我试图获得一个 WebViewLink,但是当我调用 .get 时,我只收到一个几乎没有任何文件元数据的小字典。 The documentation 使它看起来所有数据默认情况下都应该在那里,但它没有出现。我找不到任何方式来标记请求任何其他信息。

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

results = service.files().list(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(item['name'], item['id'])
        if "Target File" in item['name']:
            d = service.files().get(fileId=item['id']).execute()
            print(repr(d))

这是上面代码的输出:(格式化是我做的)

{u'mimeType': u'application/vnd.google-apps.document', 
 u'kind': u'drive#file',
 u'id': u'1VO9cC8mGM67onVYx3_2f-SYzLJPR4_LteQzILdWJgDE',
 u'name': u'Fix TVP Licence Issues'}

任何对代码感到困惑的人都缺少一些东西,这只是 API 的 quickstart page 中的基本 get_credentials 函数以及一些常量和导入。为了完整起见,以下是我的代码中未修改的所有内容:

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

那么缺少什么,我怎样才能获得 API 到 return 所有现在没有出现的额外元数据?

您在 files.list 调用中明确仅请求 idname 字段。将 webViewLink 添加到 results = service.files().list(fields="nextPageToken, files(id, name, webViewLink)").execute() 的列表中。要检索所有元数据,应使用 files/*。有关此性能优化的更多信息,请参阅 Google 驱动器文档中的 Working with partial resources

你们很亲近。使用较新版本的 Drive API v3,要检索其他元数据属性,您必须添加 fields 参数以指定要包含在部分响应中的其他属性。

在您的情况下,由于您要检索 WebViewLink属性,因此您的请求应该与此类似:

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

显示响应中的项目:

for item in items:
            print('{0} {1} {2}'.format(item['name'], item['id'], item['webViewLink']))

我还建议使用 API Explorer 尝试一下,这样您就可以查看您希望在响应中显示哪些额外的元数据属性。

祝您好运,希望对您有所帮助! :)

我编写了一个自定义函数来帮助获得一个可共享的网络 link 给定一个 file/folder id。可以获取更多信息here

def get_webViewLink_by_id(spreadsheet_id):
    
  sharable_link_response = drive_service.files().get( fileId=spreadsheet_id, fields='webViewLink').execute()

  return(sharable_link_response['webViewLink'])

print(get_webViewLink_by_id(spreadsheet_id = '10Ik3qXK4wseva20lNGUKUTBzKoywaugi6XOmRUoP-4A'))