使用Google Drive获取WebViewLinks

4
我刚开始尝试使用Google Drive API。使用快速入门指南设置了身份验证,可以打印我的文件列表,甚至可以复制。所有这些都很好用,但是我在尝试从Drive上的文件中访问数据时遇到了麻烦。特别是,我正在尝试获取WebViewLink,但是当我调用.get时,我只收到一个几乎没有任何文件元数据的小字典。 文档显示默认情况下应该有所有数据,但并没有出现。我找不到任何请求任何其他信息的标志的方法。
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“快速入门”Python版中的基本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返回所有额外的元数据,这些元数据现在都没有出现呢?


你知道是否可以指定webViewLink返回视图链接而不是编辑链接吗?这个可能吗? - Skywalker
3个回答

6
你离成功不远了。使用更新的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进行尝试,这样您就可以查看希望在响应中显示的其他元数据属性。祝好运!:)

啊哈,正是问题所在。这就是我没有仔细阅读复制的代码的后果。谢谢! - SuperBiasedMan

1

我编写了一个自定义函数,以帮助获取给定文件/文件夹ID的可共享网络链接。更多信息可以在这里找到。

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'))

1
你在文件列表调用中明确请求仅返回idname字段。将webViewLink添加到列表中,以便results = service.files().list(fields="nextPageToken, files(id, name, webViewLink)").execute()。要检索所有元数据,应使用files/*。有关此性能优化的更多信息,请参见Google Drive文档中的部分资源处理

但是"get"方法是否应该返回所有元数据?在我的情况下,这些属性是空的,我不知道为什么,即使有正确的许可权限! - Miguel
API浏览器在Files: get返回fields请求参数中指定的元数据,因此您可能会遇到不同的问题,例如,在我的应用程序中,auth/drive范围似乎已足够,而API浏览器需要更多。 - Björn
字段为空是因为我没有使用“fields”参数来获取它们,而且必须指定要获取哪些数据。 - Miguel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接