我正在用Python编写一个简单的脚本,可以从Google Apps域驱动服务下载和导出所有文件。我可以使用服务帐户创建驱动器会话,并从列表查询获得JSON输出。我还根据本文定义了下载功能:
https://developers.google.com/drive/manage-downloads
问题是这个函数返回另一个名为content的JSON输出,但是我不知道如何将文件本地存储在HDD上。 我在研究CURL是否可以在Python脚本中使用,找到了urllib/urllib2,它应该和CURL一样使用。但是,如果我尝试使用urllib2通过以下方式读取远程文件:
remote_file = urllib2.urlopen(download_url).read()
我得到401错误未初始化。
所以看起来urllib2正在工作,但不使用存储的凭据。
那么如何使用urllib/2创建授权查询呢?或者,从脚本中本地存储文件的正确方法是什么?是否还有其他python或google特定的库可以帮助我在本地存储文件?
提前谢谢。
编辑:我正在使用googleapi客户端库。问题是,函数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:
print 'An error occurred: %s' % resp
return None
else:
# The file doesn't have any content stored on Drive.
return None
这将在HDD上创建文件,但在尝试读取内容时失败。我不知道如何处理适合写入本地磁盘的内容。
编辑2:
好吧,我终于明白了。我的错误是试图在内容上使用函数read()。我只需要使用file.write(content)。
目前没有回答
相关问题 更多 >
编程相关推荐