从Google云端硬盘下载文件,并通过Google Drive python客户端将文件作为HttpResponse发送



我有Django 1.10项目,其中我有一个处理Google云端硬盘数据的模块。 目前,我的目标是将文件从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文件发送。 可能吗?请帮帮我!

查看Wesley Chun的python教程,使用python在Google Drive API:上传和下载文件中使用Python下载和上传驱动器文件,他在v2和v3中演示了这一点。

他在Google Drive的官方博客中有额外的解释和源代码:使用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))

最新更新