6

我正在使用 Python 编写简单的脚本,该脚本可以从 Google Apps 域 Drive Service 下载和导出所有文件。我能够使用服务帐户创建 Drive 会话,并且从列表查询中获取 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 Error Unathorized

所以看起来 urllib2 正在工作,但不使用存储的凭据。

那么如何使用 urllib/2 创建授权查询?或者从脚本中本地存储文件的正确方法是什么?是否有其他一些其他 python 或谷歌特定库可以帮助我在本地存储文件?

提前致谢。

编辑:我正在使用 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:
                    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)

4

2 回答 2

6

您可以从文章中尝试这个脚本。请记住使用适用于 Python 的 Google API 客户端库

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
于 2013-05-21T07:48:57.130 回答
0

下面的代码有助于将文件内容保存在本地文件中。只需在下面的代码中替换路径和文件扩展名。

if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
        print ('Status: %s' % resp)
        title = file.get('title')
        path = './data/'+title+".csv"
        file1 = open(path, 'wb')
        file1.write(content)
    else:
        print ('An error occurred: %s' % resp)
        return None
else:
    # The file doesn't have any content stored on Drive.
    return None
于 2015-12-09T08:58:49.827 回答