如何使用python-google-api下载文件 [英] How to download a file with python-google-api

查看:179
本文介绍了如何使用python-google-api下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用GoogleAPI下载文件?这是我到目前为止的内容:

How would I download a file using the GoogleAPI? Here is what I have so far:

CLIENT_ID = '255556'
CLIENT_SECRET = 'y8sR1'
DOCUMENT_ID = 'a123'
service=build('drive', 'v2')

# How to do the following line?
service.get_file(CLIENT_ID, CLIENT_SECRET, DOCUMENT_ID)

推荐答案

使用Google Drive API下载文件有多种方法.这取决于您要下载的是普通文件还是google文档(需要以特定格式导出).

There are different ways to download a file using Google Drive API. It depends on whether you are downloading a normal file or a google document (that needs to be exporteed in a specific format).

对于存储在驱动器中的常规文件,您可以使用:

for regular files stored in drive, you can either use:

alt = media,它是首选选项,例如:

alt=media and it's the preferred option, as in:

GET https://www.googleapis.com/drive/v2/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs

另一种方法是使用DownloadUrl,如下所示:

the other method is to use DownloadUrl, as in:

from apiclient import errors
# ...

def download_file(service, drive_file):
  """Download a file's content.

  Args:
    service: Drive API service instance.
    drive_file: Drive File instance.

  Returns:
    File's content if successful, None otherwise.
  """
  download_url = drive_file.get('downloadUrl')
  if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
      print 'Status: %s' % resp
      return content
    else:
      print 'An error occurred: %s' % resp
      return None
  else:
    # The file doesn't have any content stored on Drive.
    return None

对于google文档,您需要使用exportLinks并指定mime类型,而不是使用downloadUrl,例如:

For google documents, instead of using downloadUrl, you need to use exportLinks and specify the mime type, for example:

download_url = file['exportLinks']['application/pdf']

其余文档可在此处找到: https://developers.google.com/drive/web/manage-downloads

The rest of the documentation can be found here: https://developers.google.com/drive/web/manage-downloads

这篇关于如何使用python-google-api下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆