2017-07-14 209 views
0

我有Django 1.10項目,其中有一個用於使用Google Drive數據的模塊。 目前我的目標是從Google Drive下載文件到用戶的本地PC。截至目前,我有以下代碼:從Google Drive下載文件並通過Google Drive python客戶端將文件作爲HttpResponse發送到客戶端

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

查看Wesley Chun的python教程,使用python下載和上傳使用Python的驅動器文件Google Drive API: Uploading & Downloading Files,他在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)) 
補充說明和源代碼在自己的官方博客
相關問題