使用 Google Drive 获取 WebViewLinks

2024-01-06

我刚刚开始尝试使用 Google Drive API。使用快速入门指南,我设置了身份验证,我可以打印文件列表,甚至可以进行复印。所有这些都很好用,但是我在尝试从云端硬盘上的文件访问数据时遇到问题。特别是,我想得到一个WebViewLink,但是当我打电话时.get我只收到一本小字典,几乎没有任何文件的元数据。文档 https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.files.html#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'}

对于任何对代码感到困惑的人来说,缺少一些只是基本的内容get_credentials来自 API 的函数快速启动页面 https://developers.google.com/gmail/api/quickstart/python以及一些常量和导入。为了完整起见,以下是我的代码中未修改的所有内容:

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 返回所有现在没有出现的额外元数据呢?


你们非常接近。随着新版本的驱动器 API v3 https://developers.google.com/drive/v3/reference/,要检索其他元数据属性,您必须添加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浏览器 https://developers.google.com/drive/v3/reference/files/list#try-it这样您就可以查看您希望在响应中显示哪些其他元数据属性。

祝你好运,希望这能帮到你 ! :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Google Drive 获取 WebViewLinks 的相关文章

随机推荐