Glider
Loading...
Searching...
No Matches
DownloadFiles.py
Go to the documentation of this file.
1from __future__ import print_function
2
3import io
4import os
5import google.auth
6from google.oauth2.credentials import Credentials
7from googleapiclient.discovery import build
8from googleapiclient.errors import HttpError
9from googleapiclient.http import MediaIoBaseDownload
10from urllib.request import urlretrieve
11
12
13def download_file_or_folder(file_id, path):
14 """
15 Downloads a file or a folder from Google Drive
16
17 Args:
18 file_id (str): ID of the folder/file to download
19 path (str): Local path where file(s) will be downloaded
20 Returns : Nothing
21 """
22 # creds, project_id = google.auth.default()
23 # dir_path = os.path.dirname("glider/")
24 # base_path = os.path.basename(os.getcwd())
25 # full_path = dir_path+"/"+base_path
26 full_path = __file__
27 rel_path = full_path.split("/")[:-1]
28 rel_path = "/".join(rel_path)
29 try:
30 # create drive api client
31 SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive.readonly",
32 "https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.appdata", "https://www.googleapis.com/auth/drive.metadata",
33 "https://www.googleapis.com/auth/drive.photos.readonly"]
34 # SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
35 creds = Credentials.from_authorized_user_file(rel_path+"/token.json", SCOPES)
36 service = build("drive", "v3", credentials=creds)
37
38 file = service.files().get(fileId=file_id, fields="name, mimeType").execute()
39 file_name = file["name"]
40 mime_type = file["mimeType"]
41 new_path = os.path.join(path, file_name)
42 if mime_type == "application/vnd.google-apps.folder":
43 # If it's a folder, create a corresponding local directory and download its contents
44 if not os.path.exists(new_path):
45 os.makedirs(new_path)
46 results = service.files().list(q="'{}' in parents".format(file_id), fields="nextPageToken, files(id, name)").execute()
47 items = results.get("files", [])
48 for item in items:
49 download_file_or_folder(item['id'], new_path)
50 else:
51 # If it's a file, download it to the local directory
52 request = service.files().get_media(fileId=file_id)
53 fh = io.BytesIO()
54 downloader = MediaIoBaseDownload(fh, request)
55 done = False
56 while done is False:
57 status, done = downloader.next_chunk()
58 print("Download %d%%." % int(status.progress() * 100))
59 fh.seek(0)
60
61 with open(new_path, "wb") as f:
62 f.write(fh.read())
63 f.close()
64
65 except HttpError as error:
66 print("An error occurred: {}".format(error))
67 raise Exception("Some files can not be downloaded")