如何使用 python-google-api 下载文件
How to download a file with python-google-api
如何使用 GoogleAPI 下载文件?这是我目前所拥有的:
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 驱动器 API 下载文件的方法有多种。这取决于您下载的是普通文件还是 google 文档(需要以特定格式导出)。
对于存储在驱动器中的常规文件,您可以使用:
alt=media 并且它是首选选项,如:
GET https://www.googleapis.com/drive/v2/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
另一种方法是使用 DownloadUrl,如:
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个文档,不使用downloadUrl,需要使用exportLinks并指定mime类型,例如:
download_url = file['exportLinks']['application/pdf']
其余文档可在此处找到:
https://developers.google.com/drive/web/manage-downloads
如何使用 GoogleAPI 下载文件?这是我目前所拥有的:
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 驱动器 API 下载文件的方法有多种。这取决于您下载的是普通文件还是 google 文档(需要以特定格式导出)。
对于存储在驱动器中的常规文件,您可以使用:
alt=media 并且它是首选选项,如:
GET https://www.googleapis.com/drive/v2/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
另一种方法是使用 DownloadUrl,如:
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个文档,不使用downloadUrl,需要使用exportLinks并指定mime类型,例如:
download_url = file['exportLinks']['application/pdf']
其余文档可在此处找到: https://developers.google.com/drive/web/manage-downloads