return current_folder parser = argparse.ArgumentParser() parser.add_argument("root", help="The root folder of the repository. Enter exactly what's specified as 'prefix', by default that's 'git-annex'.") parser.add_argument("--token", help="If defined, access token will be stored in and loaded from this file. By default, no credentials are stored.") args = parser.parse_args() # Authentication gauth = GoogleAuth() gauth.settings['client_config_backend'] = 'settings' gauth.settings['client_config'] = {'client_id': '914459249505-ji3d9v92ealsmc4a63ns66uoj9t6mdf0.apps.googleusercontent.com', 'client_secret': 'ivD4Ms4eROu10sHc43ojgX05', 'auth_uri':'https://accounts.google.com/o/oauth2/auth', 'token_uri':'https://accounts.google.com/o/oauth2/token', 'revoke_uri': None, 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob'} if args.token: gauth.LoadCredentialsFile(args.token) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() if args.token: gauth.SaveCredentialsFile(args.token) # Counter for statistics moved_count = 0 deleted_count = 0
# In[ ]: import cv2 import time import pyautogui import os import keyboard from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive log = open('log.txt',"r+") keyboard.start_recording() gauth = GoogleAuth() gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: gauth.LocalWebserverAuth() print('rip') elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("mycreds.txt") gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) def show(mirror=False): f = 0 cam = cv2.VideoCapture(0) while True:
import os import sys import json import csv import time from datetime import datetime import requests from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("credentials.json") if gauth.credentials is None: # Authenticate if they're not there 0auth2 #gauth.LocalWebserverAuth() gauth.CommandLineAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: #Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("credentials.json") drive = GoogleDrive(gauth) file_a = drive.CreateFile({'id':'1R7i_S2vtUQdhuJu2LdhKishtFrBSUYxd'}) #download the file
class MotionUploader: def __init__(self, config_file_path): # Load config config = ConfigParser.ConfigParser() config.read(config_file_path) # GMail account credentials self.username = config.get('gmail', 'user') self.password = config.get('gmail', 'password') self.from_name = config.get('gmail', 'name') self.sender = config.get('gmail', 'sender') # Recipient email address (could be same as from_addr) self.recipient = config.get('gmail', 'recipient').split(';') self.snapshotrecipient = config.get('gmail', 'snapshotrecipient').split(';') # Subject line for email self.subject = config.get('gmail', 'subject') # First line of email message self.message = config.get('gmail', 'message') # Folder (or collection) in Docs where you want the pictures & videos to go self.folder = config.get('docs', 'folder') # Options self.delete_after_upload = config.getboolean('options', 'delete-after-upload') self.send_email = config.getboolean('options', 'send-email') self._create_gdata_client() def _create_gdata_client(self): """Create a pydrive oonnection.""" self.gauth = GoogleAuth() self.gauth.LoadCredentialsFile("/etc/motion/pydrive_auth.txt") if self.gauth.credentials is None: self.gauth.CommandLineAuth() # Authenticate if they're not there elif self.gauth.access_token_expired: self.gauth.Refresh() # Refresh them if expired else: self.gauth.Authorize() # Initialize the saved creds self.gauth.SaveCredentialsFile( "/etc/motion/pydrive_auth.txt" ) # Save the current credentials to a file self.drive = GoogleDrive(self.gauth) # Initialize the saved creds def _get_folder_resource(self): """Find and return the resource whose title matches the given folder.""" current_date = datetime.strftime(datetime.now(), '%Y-%m-%d') root_folder = self.drive.ListFile({ 'q': "title='{}' and mimeType contains 'application/vnd.google-apps.folder' and trashed=false" .format(self.folder) }).GetList()[0] current_date_folder = self.drive.ListFile({ 'q': "title='{}' and '{}' in parents and trashed=false".format( current_date, root_folder['id']) }).GetList() if current_date_folder: return current_date_folder[0] current_date_folder = self.drive.CreateFile({ 'title': current_date, "mimeType": "application/vnd.google-apps.folder", 'parents': [{ 'id': root_folder['id'] }] }) current_date_folder.Upload() return current_date_folder def _send_email(self, msg): '''Send an email using the GMail account.''' senddate = datetime.strftime(datetime.now(), '%Y-%m-%d') m = "Date: %s\r\nFrom: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" % ( senddate, self.from_name, self.sender, ", ".join( self.recipient), self.subject) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(self.username, self.password) server.sendmail(self.sender, self.recipient, m + msg) server.quit() def media_upload(self, file_path, folder_resource): '''Upload the file and return the doc''' print('Uploading image') doc = self.drive.CreateFile({ 'title': os.path.basename(file_path), 'parents': [{ u'id': folder_resource['id'] }] }) doc.SetContentFile(file_path) doc.Upload() return doc def upload_file(self, file_path): """Upload a picture / video to the specified folder. Then optionally send an email and optionally delete the local file.""" folder_resource = self._get_folder_resource() if not folder_resource: raise Exception('Could not find the %s folder' % self.folder) doc = self.media_upload(file_path, folder_resource) if self.send_email: if file_path.split('.')[-2][-8:] == 'snapshot': self.recipient = self.recipient + self.snapshotrecipient thumbnail_link = doc['thumbnailLink'] # unused at the moment media_link = doc['alternateLink'] # Send an email with thumbnail and link msg = self.message msg += '\n\n' + media_link self._send_email(msg) if self.delete_after_upload: os.remove(file_path)
def subir_archivo(self): print("Subiendo") gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) folderName = "App Inventario" # folder = drive.CreateFile({'title' : folderName, 'mimeType' : 'application/vnd.google-apps.folder'}) # folder.Upload() fileList = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() contador = 0 if len(fileList) == 0: # No hay archivos print("No hay ningun archivo, creando el folder") folder = drive.CreateFile({ 'title': folderName, 'mimeType': 'application/vnd.google-apps.folder' }) folder.Upload() contador = -1 for file in fileList: # haciendo un for para comprobar los archivos # print('Title: %s, ID: %s' % (file['title'], file['id'])) # Get the folder ID that you want if file['title'] == folderName: print("Existe el folder necesario") contador = -1 break elif file['title'] != folderName: print("Archivo sin coincidencia") print('Title: %s, ID: %s' % (file['title'], file['id'])) contador = contador + 1 if contador == len( fileList ): # si son iguales significa que no existe carpeta de la App print("Se debe crear el archivo") folder = drive.CreateFile({ 'title': folderName, 'mimeType': 'application/vnd.google-apps.folder' }) folder.Upload() # -------Parte de actualizar arc folderName = "App Inventario" folder_id = '' # creacion archivo en un folder específico # folders = drive.ListFile( # {'q': "title='" + folderName + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList() file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: if (file['title'] == folderName): folder_id = file['id'] break # 3) Build string dynamically (need to use escape characters to support single quote syntax) str = "\'" + folder_id + "\'" + " in parents and trashed=false" # 4) Starting iterating over files file_list = drive.ListFile({'q': str}).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == "database.db": file.Delete() file2 = drive.CreateFile({'parents': [{'id': folder_id}]}) file2.SetContentFile('database.db') file2.Upload() #Informar que se ha subido snackbar = Snackbar(text="Se ha realizado el respaldo") snackbar.show()
# # 848084185210-q6g400ans0ddc451tlak117dr7icvt8l.apps.googleusercontent.com # # E2k0Khce2aMFmo7144jZ7gES import os import shutil from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import sys my_path = os.path.abspath(os.path.dirname(__file__)) # gauth = GoogleAuth() # gauth.LoadCredentialsFile("mycreds.txt") gauth = GoogleAuth(settings_file=os.path.join(my_path, "settings.yaml")) gauth.LoadCredentialsFile(os.path.join(my_path, "mycreds.txt")) if gauth.credentials is None: # Authenticate if they're not there # gauth.LocalWebserverAuth() gauth.CommandLineAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile(os.path.join(my_path, "mycreds.txt")) drive = GoogleDrive(gauth) # Get last model
def CheckCredentialsFile(self, credentials, no_file=False): ga = GoogleAuth('settings/default.yaml') ga.LoadCredentialsFile(credentials) self.assertEqual(ga.access_token_expired, no_file)
class DriveManager: def __init__(self): """Create an instance of UploadDrive.""" self.gauth = GoogleAuth() self.connect() self.drive = GoogleDrive(self.gauth) def connect(self): """Connect to the drive with the flow """ # https: // github.com / gsuitedevs / PyDrive / issues / 104 self.gauth.LoadCredentialsFile("mycreds.txt") if self.gauth.credentials is None: # Authenticate if they're not there self.gauth.GetFlow() self.gauth.flow.params.update({'access_type': 'offline'}) self.gauth.flow.params.update({'approval_prompt': 'force'}) self.gauth.LocalWebserverAuth() elif self.gauth.access_token_expired: # Refresh them if expired self.gauth.Refresh() else: # Initialize the saved creds self.gauth.Refresh() # Save the current credentials to a file self.gauth.SaveCredentialsFile("mycreds.txt") def write_file_on_cloud(self, path, title="values.csv"): """Create GoogleDriveFile instance :param path: path of the file :type path: str :param title: title in google drive :type title: str """ self.connect() file1 = self.drive.CreateFile() file1.SetContentFile(path) file1['title'] = title file1.Upload() # Auto-iterate through all files that matches this query def find_file_title_on_cloud(self, title=''): """find a given file by its title on the cloud :param title:The title of the text file :type title: str :return file_id """ self.connect() file_list = self.drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == title: print('found : ' + title) return file['title'] print('file not found : ' + title) return 404 def find_file_id_on_cloud(self, title=''): """Find a file by its id on the cloud :param title:The title of the text file :type title: str :return file_id """ # results=service.files().list().execute() # file_list=results.get('items',[]) self.connect() file_list = self.drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == title: print('found : ' + title) return file['id'] return 404 def download_file_from_cloud(self, file_id, path): """Download a Drive file's content to the local filesystem. :param file_id: ID of the Drive file that will downloaded. :type file_id: str :param path: where the file is written :type path: str :return if the download succeeded """ self.connect() if self.internet_on(): local_fd = open(path + "commands.csv", "wb") request = self.drive.auth.service.files().get_media(fileId=file_id) media_request = http.MediaIoBaseDownload(local_fd, request) while True: try: download_progress, done = media_request.next_chunk() except errors.HttpError as error: print('An error occurred: %s' % error) return False if download_progress: print('Download Progress: %d%%' % int(download_progress.progress() * 100)) if done: print('Download Complete') return True else: return False def delete_file_on_cloud(self, file_title): # HTTP request DELETE """Permanently delete a file, skipping the trash. :param file_title: ID of the file to delete. :type file_title: str :return if file didn't delete """ self.connect() file_list = self.drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == file_title: print('found : ' + file_title) self.drive.auth.service.files().delete( fileId=file['id']).execute() print('file not found : ' + file_title) return 404 @staticmethod def internet_on(): """Check if the connection to the internet works :return if there is a internet connexion """ try: urlopen('http://216.58.192.142', timeout=1) return True except URLError: return False
saveFile.SetContentFile(filePath) saveFile.Upload() def downloadSaveFile(id, romsDir, gameName, gameSystem): savePath = romsDir + '/' + gameSystem + '/' + gameName + '.test' downloadFile = drive.CreateFile({'id': id}) downloadFile.GetContentFile(savePath) print("Downloading " + gameName + " to " + savePath) gauth = GoogleAuth() # These next two lines are commneted out, only needed to create the creds #gauth.CommandLineAuth() # client_secrets.json need to be in the same directory as the script #gauth.SaveCredentialsFile("gDriveCreds.txt") gauth.LoadCredentialsFile("gDriveCreds.txt") drive = GoogleDrive(gauth) save_folder_list = ListFolder('FOLDERID') save_file_list = [] for saveFile in save_folder_list: save_file_list.append(saveFile['title']) # Search /home/pi/RetroPie/roms/* for .srm and .state files romsDir = "/home/pi/RetroPie/roms" savesExt = ('.srm', '.state') for gameSystem in os.listdir(romsDir): for file in glob.glob(romsDir + "/" + gameSystem + "/*"): if file.endswith(savesExt): timeUTC = str(os.path.getmtime(file))
def main(): #Get current script path os.chdir(os.path.dirname(os.path.realpath(__file__))) #Init google auth gauth = GoogleAuth() #Load google credentials gauth.LoadCredentialsFile("mycreds.txt") #If they dont exists launch a webbrowser to authenticate user if gauth.credentials is None: gauth.LocalWebserverAuth() #If they expired refresh them elif gauth.access_token_expired: gauth.Refresh() #Else use the loaded credentials else: gauth.Authorize() #Save the credentials file for future use gauth.SaveCredentialsFile("mycreds.txt") #Init GoogleDrive with the generated authentication drive = GoogleDrive(gauth) #Get the current date and time now = datetime.datetime.now() timestamp = now.strftime('%Y-%m-%d-%H-%M') #Append date to file name file_name = timestamp + OUTPUT_FILE_SUFFIX #Check if the local output directory exists else create it if (not os.path.exists(LOCAL_OUTPUT_DIR)): os.makedirs(LOCAL_OUTPUT_DIR) #Generate the base request for direct-one-way flights from Malta request = 'flights?flyFrom=MLA&typeFlight=oneway&directFlights=1' #Generate a date range starting from the 1st of May til the end of June start_date = date(2018, 5, 1) end_date = date(2018, 6, 30) #Generate a list of dates using the date range date_list = [ date.fromordinal(i) for i in range(start_date.toordinal(), end_date.toordinal() + 1) ] final_response = {} final_response['data'] = [] #For each date in the list for i, tmp_date in enumerate(date_list): #Append the date to the request date_range = '&dateFrom=' + tmp_date.strftime( '%d/%m/%Y') + '&dateTo=' + tmp_date.strftime('%d/%m/%Y') final_request = request + date_range try: #Send request response = sendRequest(final_request) #If it is the first request being sent if i == 0: #Add header info to final response for attribute in response: if (attribute != 'data'): final_response[attribute] = response[attribute] #Add data to final response final_response['data'].extend(response['data']) except Exception as e: pass #Convert response dictionary to json json_data_string = json.dumps(final_response) #Write to local file system with open(LOCAL_OUTPUT_DIR + file_name, 'w') as out_file: out_file.write(json_data_string) #Save to Google Drive g_file = drive.CreateFile({ "parents": [{ "kind": "drive#childList", "id": "1A6gahcUQxgyjobtEFdLH_sMod5_x_2Hy" }], 'title': file_name }) g_file.SetContentString(json_data_string) g_file.Upload()
from pydrive.drive import GoogleDrive # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('-d', '--dir-id', dest='dirId', help='destination google drive folder id') parser.add_argument('filepaths', nargs='+', help='files to be upload') args = parser.parse_args() # Authentication # ref: https://stackoverflow.com/a/24542604/2605764 credentialsFilename = 'saved_user_creds.dat' gauth = GoogleAuth() gauth.LoadCredentialsFile(credentialsFilename) if gauth.credentials is None: gauth.CommandLineAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(credentialsFilename) drive = GoogleDrive(gauth) # Upload files paths = args.filepaths regProg = re.compile('^.*\/') for path in paths: try: filename = regProg.sub('', path)
import sys import time import datetime import pydrive import numpy as np import pytesseract import gphoto2 import os import csv import imutils import cv2 data='lista.csv' g_login = GoogleAuth() g_login.LoadCredentialsFile("mycreds.txt") if g_login.credentials is None: # Authenticate if they're not there g_login.LocalWebserverAuth() elif g_login.access_token_expired: # Refresh them if expired g_login.Refresh() else: # Initialize the saved creds g_login.Authorize() # Save the current credentials to a file g_login.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(g_login) file_drive = drive.CreateFile({'title': data}) file_drive.SetContentFile(data) file_drive.Upload()