我正在使用Python中的简单脚本,可以从Google Apps域Drive Service下载和导出所有文件.我能够使用服务帐户创建Drive会话,我从列表查询中获取JSON输出.我还根据这篇文章定义了下载功能:
https://developers.google.com/drive/manage-downloads
问题是这个函数返回另一个叫做内容的JSON输出,但我无法弄清楚如何在HDD上本地存储文件.我正在调查CURL是否可以在Python脚本中使用并找到urllib/urllib2,它应该像CURL一样使用.但是,如果我尝试使用urllib2来读取远程文件:
remote_file = urllib2.urlopen(download_url).read()
Run Code Online (Sandbox Code Playgroud)
我得到401 Error Unathorized.
所以它看起来像urllib2工作,但不使用存储的凭据.
那么如何使用urllib/2创建授权查询?或者在脚本中本地存储文件的正确方法是什么?还有其他一些python或google特定的库可以帮助我在本地存储文件吗?
提前致谢.
编辑:我正在使用Google API客户端库.问题是函数download_file返回一些JSON输出,但我无法将文件保存到本地存储.
我试过这样的事情:
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
title = drive_file.get('title')
path = './data/'+title
file = open(path, 'wb')
# remote_file = urllib2.urlopen(download_url).authorize().read()
file.write(content.read())
else: …Run Code Online (Sandbox Code Playgroud)