-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_api.py
160 lines (127 loc) · 5.57 KB
/
google_api.py
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
from __future__ import print_function
import unittest
import httplib2
import os, io
import Utilities.csv_utility as cs
from apiclient import discovery
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload, MediaUpload, MediaInMemoryUpload, build_http, \
HttpRequest
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
import auth
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
class google_drive_api:
drive_service=None
def __init__(self):
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'
authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME)
credentials = authInst.getCredentials()
http = credentials.authorize(httplib2.Http())
global drive_service
drive_service= discovery.build('drive', 'v3', http=http)
def listFiles(self,size):
try:
results = drive_service.files().list(
pageSize=size, fields="nextPageToken, files(id, name, mimeType)").execute()
res = {}
items = results.get('files', [])
if not items:
res = {'Error': 'No Files found ... process terminating'}
logger.debug('No Files found ... process terminating')
os._exit(0)
else:
for item in items:
logger.debug('{} : {} : {}'.format(item['name'], item['id'], item['mimeType']))
res = {'Message': items}
cs.write_to_csv(items)
return res
except Exception as e:
raise e
def uploadFile(self,filename, filepath, mimetype,chunksize):
file_metadata = {'name': filename}
media = MediaFileUpload(filepath,
mimetype=mimetype,chunksize=chunksize)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
logger.debug('File ID: %s' % file.get('id'))
def downloadFile(self,file_name, filepath):
file_id = cs.read_csv_get_Fileid(file_name)[0]
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
logger.debug("Download %d%%." % int(status.progress() * 100))
with io.open(filepath, 'wb') as f:
fh.seek(0)
f.write(fh.read())
def downloadFile_after_searching_Api(self,file_name, filepath):
file_id = self.searchFile(10, f"name contains '{file_name}'")[0]['id']
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
logger.debug("Download %d%%." % int(status.progress() * 100))
with io.open(filepath, 'wb') as f:
fh.seek(0)
f.write(fh.read())
def downloadAllFile_after_searching_Api(self,file_name, filepath):
file_id = self.searchFile(5, f"name contains '{file_name}'")
counter = 0
for file in file_id:
request = drive_service.files().get_media(fileId=file['id'])
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
try:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))
logger.debug("Download %d%%." % int(status.progress() * 100))
except Exception as e:
counter+=1
logger.error(" Unable to download file {}".format(e))
done=True
with io.open(filepath, 'wb') as f:
fh.seek(0)
f.write(fh.read())
if counter>0:
raise Exception(f'{counter} Files Didnt get Downloaded ')
os._exit(0)
def createFolder(self,name):
file_metadata = {
'name': name,
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive_service.files().create(body=file_metadata,
fields='id').execute()
logger.debug('Folder ID: %s' % file.get('id'))
def searchFile(self,size, query):
try:
results = drive_service.files().list(
pageSize=size, fields="nextPageToken, files(id, name, kind, mimeType)", q=query).execute()
except Exception as e:
logger.error(f'Error occured due to{ e} valid parameters size: int/float 10/10.5 not String "10.5" and querry valid string ')
raise Exception(e)
items = results.get('files', [])
if not items:
logger.debug('No files found.')
else:
logger.debug('Files:')
for item in items:
logger.debug('{0} ({1})'.format(item['name'], item['id']))
return items
# uploadFile('unnamed.jpg','unnamed.jpg','image/jpeg')
# downloadFile('Blue Jeans','BlueJeans.pdf')
# createFolder('Google')
# searchFile(10,"name contains 'redbus' and mimeType contains 'image'")
# downloadFile_after_searching_Api('BluL̥e Jeans','BlueJeans.pdf')
# listFiles(10)