Skip to content

Commit fbe7d60

Browse files
committed
Added files
1 parent 17cf16c commit fbe7d60

File tree

2 files changed

+190
-0
lines changed

2 files changed

+190
-0
lines changed

README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# gdrive-interact
2+
3+
Easily allows users to upload/download files to/from their Google Drive via Google Drive API.
4+
5+
## Requirements
6+
- Python
7+
- pip modules
8+
- pydrive
9+
- Google Drive API credentials file
10+
11+
12+
## Usage
13+
14+
```py
15+
import gdrive_interact
16+
17+
# Specify path to credentials file of Google Drive API
18+
gdrive_interact.set_client_config_path("client_secrets.json")
19+
20+
# Authenticate
21+
client = gdrive_interact.authenticate_client("creds.txt") # Saves access token credentials. If file does not exist, one-time manual sign-in is done via browser and the file is auto-generated.
22+
23+
# Get id of file/folder
24+
folder_id = gdrive_interact.get_id(client, "<drive_folder_name>/<drive_folder_name>/.../<folder_or_file_name>")
25+
26+
# Get list of files in a folder
27+
file_list = gdrive_interact.list_files(client, folder_id)
28+
29+
# Upload a file
30+
gdrive_interact.upload_file(client, '<drive_folder_name>/<drive_folder_name>/.../<drive_file_name>', "C:/.../<system_directory_name>", "<system_file_name>")
31+
32+
# Download a file
33+
gdrive_interact.download_file(client, "<drive_folder_name>/<drive_folder_name>/.../<drive_file_name>", "C:/.../<system_directory_name>")
34+
35+
# Download a folder
36+
gdrive_interact.download_folder(client, "<drive_folder_name>/<drive_folder_name>/.../<drive_folder_name>", "C:/.../<system_directory_name>", files_only=False) # Set files_only = True if you only want the files within, and not the folder itself
37+
```
38+
39+
## How to create a credentials file
40+
In order to contact and successfully authenticate with your Drive account, you must have a credentials file. In the above example, it is `client_secrets.json`. To create one, see [Google's API Console](console.developers.google.com). Create a project and enable Google Drive API. Download the credentials file.

gdrive_interact.py

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
from pydrive.drive import GoogleDrive
2+
from pydrive.auth import GoogleAuth
3+
import os
4+
5+
6+
class client:
7+
pass
8+
9+
10+
11+
def set_client_config_path(path_to_secrets_file):
12+
GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = path_to_secrets_file
13+
14+
15+
def authenticate_client(creds_path):
16+
17+
client.gauth = GoogleAuth()
18+
gauth=client.gauth
19+
20+
# Try to load saved client credentials
21+
gauth.LoadCredentialsFile(creds_path)
22+
23+
if gauth.credentials is None:
24+
# Authenticate if they're not there
25+
gauth.GetFlow()
26+
gauth.flow.params.update({'access_type': 'offline'})
27+
gauth.flow.params.update({'approval_prompt': 'force'})
28+
gauth.LocalWebserverAuth()
29+
elif gauth.access_token_expired:
30+
# Refresh them if expired
31+
gauth.Refresh()
32+
else:
33+
# Initialize the saved creds
34+
gauth.Authorize()
35+
36+
# Save the current credentials to a file
37+
gauth.SaveCredentialsFile(creds_path) #Note that credentials will expire after some time and may not refresh. When this happens, delete the mycreds.txt file and run the program again. A new and valid mycreds.txt will automatically be created.
38+
client.drive = GoogleDrive(client.gauth)
39+
40+
return client
41+
42+
43+
44+
def list_files(client, folder_id):
45+
46+
# authenticate_client()
47+
48+
return client.drive.ListFile({'q': f"'{folder_id}' in parents and trashed=false"}).GetList()
49+
50+
51+
def get_id(client, folder_path):
52+
53+
fileID = None
54+
55+
try:
56+
57+
folder_path = folder_path.split('/')
58+
59+
fileList = client.drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
60+
61+
for file in fileList:
62+
if file['title']==folder_path[0]:
63+
fileID = file['id']
64+
break
65+
folder_path.pop(0)
66+
67+
for folder_name in folder_path:
68+
fileList = client.drive.ListFile({'q': f"'{fileID}' in parents and trashed=false"}).GetList()
69+
for file in fileList:
70+
if file['title']==folder_name:
71+
fileID = file['id']
72+
break
73+
74+
except:
75+
76+
fileID = False
77+
78+
finally:
79+
80+
return fileID
81+
82+
83+
def upload_file(client, target_folder_path , home_path, file_name):
84+
85+
# authenticate_client()
86+
87+
target_id = get_id(client, target_folder_path)
88+
if target_id == False:
89+
print(f"[ ERROR in gprocesses.py ] : {target_folder_path} not found.")
90+
return False
91+
home_path = rf"{home_path}"
92+
93+
f = client.drive.CreateFile({
94+
'title': file_name,
95+
'parents': [{'id': target_id}]
96+
})
97+
f.SetContentFile(os.path.join(home_path, file_name))
98+
f.Upload()
99+
100+
# Example: upload_file('<drive_folder_name>/<drive_folder_name>/.../<file_name>',rf"C:/.../<system_directory_name>", "<file_name>")
101+
102+
103+
104+
def download_file(client, target_file_path, home_path):
105+
106+
# authenticate_client()
107+
108+
target_id = get_id(client, target_file_path)
109+
if target_id == False:
110+
print(f"[ ERROR in gprocesses.py ] : {target_file_path} not found.")
111+
return False
112+
home_path = rf"{home_path}"
113+
114+
file = client.drive.CreateFile({'id': target_id})
115+
working_path = os.getcwd()
116+
os.chdir(home_path)
117+
file.GetContentFile(file['title'])
118+
os.chdir(working_path)
119+
120+
121+
# Example: download_file("<drive_folder_name>/<drive_folder_name>/.../<file_name>", "C:/.../<system_directory_name>")
122+
123+
124+
def download_folder(client, target_folder_path, home_path, files_only = True):
125+
#If files_only = True, only files will be downloaded. If files_only = False, parent folder containing the files will be downloaded along with its contents.
126+
# authenticate_client()
127+
128+
working_path = os.getcwd()
129+
130+
target_id = get_id(client, target_folder_path)
131+
132+
if target_id == False:
133+
print(f"[ ERROR in gprocesses.py ] : {target_folder_path} not found.")
134+
return False
135+
home_path = rf"{home_path}"
136+
137+
if files_only == False:
138+
home_path = os.path.join(home_path,target_folder_path.split('/')[len(target_folder_path.split('/'))-1])
139+
print(home_path)
140+
os.mkdir(home_path, 0o666)
141+
142+
files=list_files(client, target_id)
143+
for file in files:
144+
file = client.drive.CreateFile({'id': file['id']})
145+
os.chdir(home_path)
146+
file.GetContentFile(file['title'])
147+
os.chdir(working_path)
148+
149+
150+
# download_folder ("<drive_folder_name>/<drive_folder_name>/.../<drive_folder_name>", "C:/.../<system_directory_name>")

0 commit comments

Comments
 (0)