def upload(): os.system('python --version > file.txt') CLIENT_SECRET_FILE = 'client_secret.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] folder_id = '1Bz75IcdiIB-bdmc68ux-v42hlyolup2G' service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) file_names = ['file.txt'] mime_types = ['text/plain'] for file_name, mime_type in zip(file_names, mime_types): file_metadata = {'name': file_name, 'parents': [folder_id]} media = MediaFileUpload('./{0}'.format(file_name), mimetype=mime_type) service.files().create(body=file_metadata, media_body=media, fields='id').execute() #try: # main() #except: # print("error")
class google_drive_scrape(object): def __init__(self): CLIENT_SECRET_FILE = 'client_secret_GoogleCloudDemo.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ["https://www.googleapis.com/auth/drive"] self.service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) def search(self, search_term): results = self.service.files().list( q="fullText contains \'" + search_term + "\' or name contains \'" + search_term + "\'", spaces='drive', fields="nextPageToken, files(id, name, webViewLink)").execute() items = results.get('files', []) f = open("search results.html", "w") if not items: print('No files found in Google drive.') else: f.write("Files found in Google Drive:" + '\n') for item in items: # print('{0} ({1})'.format(item['name'], item['webViewLink'])) f.write('<li>' + '<a href=\"' + item['webViewLink'] + '\"</a>' + '</li>') f.write(item['name']) f.close()
class EOS_DOWNLOADER(): def __init__(self, fileId, savedFileName): self.CLIENT_SECRET_FILE = 'D:\\Coding\\Py\\DriveAPI\\credentials.json' self.API_NAME = 'drive' self.API_VERSION = 'v3' self.SCPOES = ['https://www.googleapis.com/auth/drive'] self.fileId = fileId self.savedFileName = savedFileName def launch(self): self.service = Create_Service(self.CLIENT_SECRET_FILE, self.API_NAME, self.API_VERSION, self.SCPOES) self.request = self.service.files().get_media(fileId=self.fileId) self.fh = io.BytesIO() self.downloader = MediaIoBaseDownload(fd=self.fh, request=self.request) self.status = self.downloader.next_chunk()[0].progress() self.fh.seek(0) with open(f"D:\\EOSs\\{self.savedFileName}", 'wb+') as self.f: self.f.write(self.fh.read()) self.status = self.status == 1
def exportFile(): CLIENT_SECRET_FILE = "client_secret_290484746034-g2jo5esvo50gs2ckfenl4c172m8rflps.apps.googleusercontent.com.json" API_Name = 'drive' API_Version = "v3" SCOPES = [ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.metadata' ] service = Create_Service(CLIENT_SECRET_FILE, API_Name, API_Version, SCOPES) file_id = ["1p_RVPF0YjMOX1z2XZeStz_wEbt4OqOACy2mjLz4-hls"] file_name = [sys.argv[1]] for file_id, file_name in zip(file_id, file_name): request = service.files().export_media(fileId=file_id, mimeType='text/plain') fh = io.BytesIO() downloader = MediaIoBaseDownload(fd=fh, request=request) done = False while not done: status, done = downloader.next_chunk() print("Download Progress {0}".format(status.progress() * 100)) fh.seek(0) most_recent_zoom_folder_path = ZOOM_FOLDER_PATH + "/" + find_most_recent_zoom_folder( ) with open(os.path.join(most_recent_zoom_folder_path, file_name), 'wb') as f: f.write(fh.read()) f.close()
"client_id": client_id, "client_secret": client_secret, "refresh_token": refresh_token } authorization_url = "https://www.googleapis.com/oauth2/v4/token" r = requests.post(authorization_url, data=params) if r.ok: return r.json()['access_token'] else: return None CLIENT_SECRET_FILE = 'client_secret.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) folder_id ='1GJnQYG8hc7F6H0oH2imFQXO7gURhJISY' query = f"parents = '{folder_id}'" response = service.files().list(q=query).execute() files = response.get('files') nextPageToken = response.get('nextPageToken') results = service.files().list( pageSize=1,fields="files(webViewLink)").execute() print(results)
connOracle.close() filename.close() print("Successfull") CLIENT_SECRET_FILE = 'client_secret.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) folder_id = '1GJnQYG8hc7F6H0oH2imFQXO7gURhJISY' file_names = [enterprise_num + '.csv', 'w'] mime_types = ['text/csv'] for file_name, mime_type in zip(file_names, mime_types): file_metadata = {'name': file_name, 'parents': [folder_id]} media = MediaFileUpload(file_name, mimetype=mime_type) service.files().create(body=file_metadata, media_body=media, fields='id').execute() query = f"parents = '{folder_id}'" response = service.files().list(q=query).execute() files = response.get('files') nextPageToken = response.get('nextPageToken') results = service.files().list(pageSize=1, fields="files(webViewLink)").execute() print(results)
import os import io from googleapiclient.http import MediaIoBaseDownload from googleapiclient.discovery import build import pickle from Google import Create_Service GPATH = os.path.dirname(os.path.abspath(__file__)) file_id = '1hn1J6gEXMfXOPKzarXm1yQ4cnJhbgjciLSn0gyC7RfQ' service = Create_Service(f'{GPATH}/credentials.json', 'drive', 'v3', ['https://www.googleapis.com/auth/drive.readonly']) request = service.files().export_media(fileId=file_id, mimeType='application/pdf') fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print(f'Progress: {status.progress() * 100}') fh.seek(0) with open(f'{GPATH}/../static/resume.pdf', 'wb') as f: f.write(fh.read())
# # file1.Upload() from Google import Create_Service from googleapiclient.http import MediaFileUpload CLIENT_SECRET_FILE = 'client_secrets.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) folder_id = '1fgOX8hScgzxXEADZX9_yO462MMYtrKlJ' file_names = ['Covid19.XLSX', 'covid2019.html'] mime_types = [ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/html' ] for file_name, mime_type in zip(file_names, mime_types): file_metadata = {'name': file_name, 'parents': [folder_id]} media = MediaFileUpload(filename=file_name, mimetype=mime_type) service.files().create(body=file_metadata, media_body=media, fields='id').execute() # print(dir(service)) # http://localhost:8080
API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] FOLDER_PATH = Path("cached_folder.txt") FOLDER_ID = "" service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) # the file exists if FOLDER_PATH.exists(): # the file exists but doesn't contain the folder ID if FOLDER_PATH.stat().st_size == 0: print( "No folder ID exists. Retrieving folder: [{0}]'s ID from Google Drive." .format(folder_name)) result = service.files().list(q="name='{0}'".format(folder_name), spaces='drive', fields='files(name, id)').execute() cached_id = open("cached_folder.txt", "w") cached_id.write(result.get('files')[0]['id']) cached_id.close() FOLDER_ID = result.get('files')[0]['id'] # the file exists and contains the folder's ID elif FOLDER_PATH.stat().st_size > 0: print( "Folder ID exists. Retrieving folder: [{0}]'s ID from cache.". format(folder_name)) cached_id = open("cached_folder.txt", "r") FOLDER_ID = cached_id.readline() cached_id.close()
#579190987864-n52eb9hc3c77nbthnsfs054h46djgijv.apps.googleusercontent.com #2ZbqaMRogyNscImGnZ5uUJ5Q import io import os from Google import Create_Service from googleapiclient.http import MediaIoBaseDownload CLIENT_SECRET_FILE='credentials.json' API_NAME='drive' API_VERSION='v3' SCOPES=['https://www.googleapis.com/auth/drive'] service= Create_Service(CLIENT_SECRET_FILE, API_NAME,API_VERSION,SCOPES) file_id=['1AeFOV-BewH-sY_KSCMiFN9FCtOOrtDMPCRmVT0ihXqo'] file_name=['intento.xlms'] request=service.files().get_media(fields=file_id) fh=io.BytesIO() downloader=MediaIoBaseDownload(fd=fh,request=request) done=False while not done: status,done=downloader.next_chunk() print("downloadprogres {0}".format(status.progress()*100)) fh.seek(0) with open(os.path.join('./Desktop',file_name), 'wb') as f: f.write(fh.read()) f.close()
data = sheet.get_all_records() # Get a list of all records length = len(data) # gives the number of items in the sheet CLIENT_SECRET_FILE = 'client.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) folder_id = '1Ua3nGP8E2bPmfhFNapVtnuRhFKLRDque' query = f"parents = '{folder_id}'" response = service.files().list(q=query).execute() files = response.get('files') nextPageToken = response.get('nextPageToken') while nextPageToken: response = service.files().list(q=query).execute() files.extend(response.get('files')) nextPageToken = response.get('nextPageToken') pd.set_option('display.max_columns', 100) pd.set_option('display.max_rows', 500) pd.set_option('display.min_rows', 500) pd.set_option('display.max_colwidth', 150) pd.set_option('display.width', 200) pd.set_option('expand_frame_repr', True) df = pd.DataFrame(files)
def clicked2(self): #For Certificate Generation #Using Google APIs CLIENT_SECRET_FILE = 'Oauth Credentials.json' API_NAME = 'sheets' API_VERSION = 'v4' SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) CLIENT_SECRET_FILE1 = 'Oauth Credentials.json' API_NAME1 = 'drive' API_VERSION1 = 'v3' SCOPES1 = ['https://www.googleapis.com/auth/drive'] service1 = Create_Service(CLIENT_SECRET_FILE1, API_NAME1, API_VERSION1, SCOPES1) #Taking input from the screen fspreadsheet_id = str(self.lineEdit_7.text()) workshop = str(self.lineEdit_8.text()) name_f = str(self.lineEdit_9.text()) name_cs = str(self.lineEdit_11.text()) name_cs = name_cs.split(',') name_c = list() for i in range(len(name_cs)): name_c.append(int(name_cs[i])) name_c = tuple(name_c) ycoord = int(str(self.lineEdit_10.text()) ) #For determining position of Name on template content = str(self.textEdit.toPlainText()) name_s = int(self.lineEdit_20.text()) content_f = str(self.lineEdit_12.text()) content_cs = str(self.lineEdit_13.text()) content_cs = content_cs.split(',') content_c = list() for i in range(len(content_cs)): content_c.append(int(content_cs[i])) content_c = tuple(content_c) content_s = int(self.lineEdit_19.text()) uqid_f = str(self.lineEdit_18.text()) uqid_cs = str(self.lineEdit_15.text()) uqid_cs = uqid_cs.split(',') uqid_c = list() for i in range(len(uqid_cs)): uqid_c.append(int(uqid_cs[i])) uqid_c = tuple(uqid_c) uqid_s = int(self.lineEdit_14.text()) temp_location = str(self.lineEdit_16.text()) save_location = str(self.lineEdit_17.text()) #Reading Data from spreadsheet into List final = service.spreadsheets().values().get( spreadsheetId=fspreadsheet_id, range='Sheet1', majorDimension='ROWS').execute() final = final['values'] count = len(final) content = content.split(',') #Creating new folder on Google Drive drivename = 'Certificates ' + workshop file_metadata = { 'name': drivename, 'mimeType': 'application/vnd.google-apps.folder' } service1.files().create(body=file_metadata).execute() #folderid = input('Enter folder ID') text, result = QtWidgets.QInputDialog.getText( self, 'Folder ID', 'Enter the folder ID created in Google Drive') if result == True: folderid = text #Generating Certificates with Name,Unique ID,etc. using PIL for i in range(1, count): name = final[i][0] uqid = final[i][3] img = Image.open( temp_location) #Opening the img from user entered location draw = ImageDraw.Draw(img) W, H = img.size font = ImageFont.truetype(name_f, name_s) w, h = draw.textsize(name, font) location = ((W - w) / 2, ycoord) draw.text(location, name, fill=name_c, font=font) adjust = 0 for i in range(len(content)): font2 = ImageFont.truetype(content_f, content_s) #Making adjustments and setting coordinates for the text to be added on image w1, h1 = draw.textsize(content[i], font2) location2 = ((W - w1) / 2, ycoord + 150 + adjust) draw.text(location2, content[i], fill=content_c, font=font2) adjust += 40 font3 = ImageFont.truetype(uqid_f, uqid_s) w2, h2 = draw.textsize(uqid, font3) location3 = (150, 220) draw.text(location3, uqid, fill=uqid_c, font=font3) img = img.convert('RGB') img.save(save_location + '/' + name + '.jpg') #Saving the image locally on laptop #Uploading the image on Google Drive in the folder created earlier uploadname = name + '.jpg' mimetype2 = 'image/jpeg' file2_metadata = {'name': uploadname, 'parents': [folderid]} media = MediaFileUpload(save_location + '/' + name + '.jpg', mimetype=mimetype2) service1.files().create(body=file2_metadata, media_body=media, fields='id').execute() message3 = QtWidgets.QMessageBox.about( self, 'Info', 'All Certificates have been generated and uploaded')
class DriveAPI: def __init__(self): self.config = dotenv_values("resources/.env") self.CLIENT_SECRET_FILE = 'resources/client_secret.json' self.API_NAME = 'drive' self.API_VERSION = 'v3' self.SCOPES = ['https://www.googleapis.com/auth/drive'] self.service = Create_Service(self.CLIENT_SECRET_FILE, self.API_NAME, self.API_VERSION, self.SCOPES) def getUserData(self) -> dict: return self.service.about().get(fields="user").execute() def createRemoteNFS(self): """ Creates the RemoteNFS folder for new users. """ file_metadata = { 'name': 'RemoteNFS', 'mimeType': 'application/vnd.google-apps.folder' } self.service.files().create(body=file_metadata).execute() def createFolder(self, folderName: str, parentFolderId: str = ""): if parentFolderId != "": parents = [parentFolderId] else: parents = [self.config['PARENT_FOLDER']] file_metadata = { 'name': folderName, 'mimeType': 'application/vnd.google-apps.folder', 'parents': parents } self.service.files().create(body=file_metadata).execute() def deleteFolder(self, folderId): self.service.files().delete(**{'fileId': folderId}).execute() def listFiles(self, count: int = 10) -> [str]: """ Give count as negative to list all files. """ response = self.service.files().list().execute()['files'] if count > 0: result = [file['name'] + ":" + file['id'] for file in response[:count]] else: result = [file['name'] + ":" + file['id'] for file in response] return result def getFilesData(self) -> {str:str}: """ Will return a dict with filename as key and fileId as value """ response = self.service.files().list().execute()['files'] return response def getFileIds(self) -> {str:str}: """ Will return a dict with filename as key and fileId as value """ response = self.service.files().list().execute()['files'] names = [file['name'] for file in response] ids = [file['id'] for file in response] result = dict() for k, v in zip(names, ids): result[k] = v return result def uploadFile(self, path: str, parentFolderId: str = ""): """ Path must be absolute path to the file, and must also include file name and extension Path must use / and not \\ You can use utils.sanitizeFilePath() to convert \\ to / """ if parentFolderId != "": parents = [parentFolderId] else: parents = [self.config['PARENT_FOLDER']] if '/' in path: fileName = path.split('/')[-1] else: fileName = path.split('\\')[-1] fileMetadata = { 'name': fileName, 'parents': parents } # TODO: Encrypt file here crypto.encryptFile(path, self.config['PASSWORD']) # logic to find mime types _mimeType = mimetypes.guess_type(path) mimeType = _mimeType[0] if mimeType == None: raise Exception(f'Mime type of file: {fileName} could not be guessed.') media = MediaFileUpload('encrypted.file', mimetype=mimeType) response = self.service.files().create( body=fileMetadata, media_body=media, fields='id' ).execute() return fileName # return response['id'] def downloadFile(self, fileId: str, fileName: str): request = self.service.files().get_media(fileId=fileId) fh = io.BytesIO() downloader = MediaIoBaseDownload(fd=fh, request=request) done = False while not done: status, done = downloader.next_chunk() print(f'Download progress {status.progress() * 100}') fh.seek(0) with open(os.path.join('./downloads/', fileName), 'wb') as f: f.write(fh.read()) f.close() decrypted = crypto.decryptFile(os.path.join('./files/', fileName), self.config['PASSWORD']) with open(os.path.join('./downloads/', fileName), 'wb') as f: f.write(decrypted) f.close() def deleteFile(self, fileId): self.service.files().delete(**{'fileId': fileId}).execute()
from googleapiclient.http import MediaIoBaseDownload CLIENT_SECRET_FILE = 'client_secret.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) file_ids = [ '1SML1QNgHzt-iUPTjfmV__UzPdg7xGErq', '1PFhFIB25D9StfQU4qnuOh6kPdH9mchaS' ] file_names = ['techFeasDoc.docx', 'paintAch.png'] for file_id, file_name in zip(file_ids, file_names): request = service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fd=fh, request=request) done = False while not done: status, done = downloader.next_chunk() print('download progres {0}'.format(status.progress() * 100)) fh.seek(0) with open(os.path.join('./files', file_name), 'wb') as f: f.write(fh.read()) f.close()