如何使用Python脚本从Drive API下载文件

时间:2013-05-21 07:34:46

标签: python file download google-drive-api google-apps

我正在使用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特定的库可以帮助我在本地存储文件吗?

提前致谢。

编辑:我正在使用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上创建文件,但在尝试读取内容时会失败。我不知道如何处理内容以适合写入本地磁盘。

EDIT2:

好的,所以我终于搞清楚了。我的错误是我试图在内容上使用函数read()。我只需要使用 file.write(content)

2 个答案:

答案 0 :(得分:6)

您可以从the article尝试此脚本。请记住使用Google APIs Client Library for Python

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

答案 1 :(得分: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