从Google云端硬盘下载文件并通过Google云端硬盘客户端

时间:2017-07-14 18:29:40

标签: python django google-drive-api

我有Django 1.10项目,其中有一个用于处理Google Drive数据的模块。 目前,我的目标是将文件从Google云端硬盘下载到用户的本地PC。截至目前,我有以下代码:

def a_files_google_download(request):
   #...
   service = build("drive", "v2", http=http)
   download_url = file.get('downloadUrl')
   resp, content = service._http.request(download_url)
   fo = open("foo.exe", "wb")
   fo.write(content)

我陷入困境,不知道如何将fo作为HttpResponse传递。 显然,我事先并不知道文件类型。它可以是.mp3,.exe,。pdf ......无论文件类型如何,代码都应该有效。 另外,我不想将文件作为zip文件发送。 可能吗 ?请帮帮我!

1 个答案:

答案 0 :(得分:1)

查看Wesley Chun的python教程,使用python在Google Drive API: Uploading & Downloading Files中使用Python下载和上传驱动文件,并在v2和v3中对其进行解除。

Google Drive: Uploading & Downloading files with Python

的官方博客中有其他说明和源代码
from __future__ import print_function
import os

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store, flags) \
            if flags else tools.run(flow, store)
DRIVE = build('drive', 'v2', http=creds.authorize(Http()))

FILES = (
    ('hello.txt', False),
    ('hello.txt', True),
)

for filename, convert in FILES:
    metadata = {'title': filename}
    res = DRIVE.files().insert(convert=convert, body=metadata,
            media_body=filename, fields='mimeType,exportLinks').execute()
    if res:
        print('Uploaded "%s" (%s)' % (filename, res['mimeType']))

if res:
    MIMETYPE = 'application/pdf'
    res, data = DRIVE._http.request(res['exportLinks'][MIMETYPE])
    if data:
        fn = '%s.pdf' % os.path.splitext(filename)[0]
        with open(fn, 'wb') as fh:
            fh.write(data)
        print('Downloaded "%s" (%s)' % (fn, MIMETYPE))