如何使用python-google-api下载文件
问题描述:
如何使用GoogleAPI下载文件?这是我到目前为止:如何使用python-google-api下载文件
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下载文件。这取决于您是下载普通文件还是谷歌文档(需要以特定格式导出)。
存储在驱动器的常规文件,你可以使用:
ALT =媒体,它是更好的选择,如:
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
对于谷歌文档,而不是使用downloadUrl,你需要使用exportLinks并指定MIME类型,例如:
download_url = file['exportLinks']['application/pdf']
文档的其余部分可以在这里找到: https://developers.google.com/drive/web/manage-downloads
你需要获得用户令牌第一....那么你就可以得到的文件像'重定向(“HTTP:// API .google.com/authorize?client_id = 255556&redirect_uri = http://127.0.0.1:5000/result“)'也许 – 2015-02-06 00:59:57