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

Ben*_*ato 5 python file download google-apps google-drive-api

我正在使用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:
                    print 'An error occurred: %s' % resp
                    return None
    else:
            # The file doesn't have any content stored on Drive.
            return None
Run Code Online (Sandbox Code Playgroud)

这会在HDD上创建文件,但在尝试读取内容时会失败.我不知道如何处理内容以适合写入本地磁盘.

EDIT2:

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

小智 6

您可以从文章中尝试此脚本.请记住使用适用于PythonGoogle 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
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回复,实际上这正是我正在使用的.但问题是这个函数返回的内容只是一个JSON输出,但我无法弄清楚如何将文件保存到本地存储(HDD). (2认同)