2016/10/31

Google Drive API - How to find file id by filename and download non Google Doc files to local storage using Python

This tutorial is based on Google Drive API v3 and Python 2.7.9.

The code below allows its user to specify the name of the file to be searched for on his/her own Google Drive. Once the file is found, the user will then be prompted on whether to download the file to the local storage or not. The download is limited to non Google Doc files. For Google Doc files, please refer to the sample code at http://wei48221.blogspot.tw/2016/10/google-drive-api-uploading-downloading.html.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from __future__ import print_function
import os
import sys
# The following 2 imports are needed for file download
import io
from apiclient.http import MediaIoBaseDownload

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)
#    creds = tools.run_flow(flow, store, flags) \
#            if flags else tools.run(flow, store)
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))

# Find the file id

filename = sys.argv[1]
query = "name contains " + "'" + filename +"' and trashed=false"

res = DRIVE.files().list(q=query, fields='files(id, name)').execute()

#When there is only one unique file on Google Drive, use the below code to find its id
f = res.get('files')
#print("res = ")
#print(res)
#print("f = ")
#print(f)
if f:
  print ("File Found!")
  print ("Name =", f[0].get('name'))
  print ("id =", f[0].get('id'))
  #print (f[0].get('name'), f[0].get('id'))
  file_id = f[0].get('id')
  file_name = f[0].get('name')
else:
  print("File Not Found!!")

#The following code will work, but there will be trouble if there are multiple files of the same name on Google Drive
#for f in res.get('files', []):
#   print(f.get('name'), f.get('id'))
#file_id = f.get('id')

if f:
  var = raw_input("Download file? (y/n)")
  print ("You entered", var)
  
if var == 'y':

#The following code is for downloading non Google Doc files.
#References:
#  https://developers.google.com/drive/v3/web/manage-downloads
#  http://stackoverflow.com/questions/36173356/google-drive-api-download-files-python-no-files-downloaded
#
#For Google Doc files, use the export() method.
#Reference:
#  http://wei48221.blogspot.tw/2016/10/google-drive-api-uploading-downloading.html 

  print ("--Download File--")
  request = DRIVE.files().get_media(fileId=file_id)
  fh = io.FileIO(file_name, 'wb')
  downloader = MediaIoBaseDownload(fh, request)
  done = False
  while done is False:
        status, done = downloader.next_chunk()
        print ("Download %d." % int(status.progress() * 100))
else:
  print ("--No Download--")
print ("Program terminated normally")

Result


References

Non Google Doc File Download:

https://developers.google.com/drive/v3/web/manage-downloads

http://stackoverflow.com/questions/36173356/google-drive-api-download-files-python-no-files-downloaded

Google Doc File Download:

http://wei48221.blogspot.tw/2016/10/google-drive-api-uploading-downloading.html

No comments:

Post a Comment