def setUp(self): gauth = GoogleAuth() gauth.credentials = OAuth2Credentials.from_json(credentials) gauth.client_config = client_config gauth.settings["client_config_backend"] = "settings" drive = GoogleDrive(gauth) self.fs = GoogleDriveFS(drive)
def main(args=sys.argv): """The main function for the erpmtics_agent program.""" logger.debug(args) try: logger.debug("Init the app") id = "*****@*****.**" # from google API console - convert private key to base64 or load from file #key = base64.b64decode(...) credentials = SignedJwtAssertionCredentials(id, key, scope='https://www.googleapis.com/auth/drive') credentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = credentials drive = GoogleDrive(gauth) sys.exit() """ gauth = GoogleAuth() gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) file1 = drive.CreateFile({'title': 'Hello.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt' file1.SetContentString('Hello World!') # Set content of the file from given string file1.Upload() """ except ImportError: raise except Exception, e: raise
def init_creds(credsb64): GDriveSync.LOCAL_TZ_OFFSET = GDriveSync.local_time_offset() if GDriveSync.CREDSB64 == credsb64: return creds_json = base64.b64decode(credsb64) creds = OAuth2Credentials.from_json(creds_json) GDriveSync.CREDS = creds GDriveSync.CREDSB64 = credsb64 gauth = GoogleAuth() gauth.settings = { 'client_config_backend': 'settings', 'client_config_file': 'client_secrets.json', 'save_credentials': False, 'oauth_scope': ['https://www.googleapis.com/auth/drive'], 'client_config': { 'client_id': creds.client_id, 'client_secret': creds.client_secret, 'auth_uri': GOOGLE_AUTH_URI, 'token_uri': GOOGLE_TOKEN_URI, 'revoke_uri': GOOGLE_REVOKE_URI, 'redirect_uri': 'http://juliabox.org/jboxauth/google/' } } gauth.LoadClientConfigSettings() gauth.credentials = creds GDriveSync.GAUTH = gauth GDriveSync.DRIVE = GoogleDrive(gauth)
def get_drive(): scopes = ['https://www.googleapis.com/auth/drive.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'service_account_key.json', scopes) credentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = credentials return GoogleDrive(gauth)
def authenticate(config): svc_user_id = config.get("drive", "service_user_email") svc_scope = "https://www.googleapis.com/auth/drive" svc_key_file = config.get("drive", "key_file") svc_key = open(svc_key_file, "rb").read() gcredentials = SignedJwtAssertionCredentials(svc_user_id, svc_key, scope=svc_scope) gcredentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = gcredentials return gauth
def _copy_drive(self): '''Create a deep copy of the GoogleAuth object, and the GoogleDrive object for use by another thread. :returns: a tuple with the copies of the GoogleAuth and the GoogelDrive object''' gauth = GoogleAuth(settings_file=self._settings_yaml) gauth.credentials = self.gauth.credentials gauth.http = None gauth.Authorize() drive = Drive(gauth) return (gauth, drive)
def authenticate(config): #logger.debug("OAuth2 Authentication - Starting") svc_user_id = config.get('drive', 'service_user_email') svc_scope = "https://www.googleapis.com/auth/drive" svc_key_file = config.get('drive', 'key_file') svc_key = open(svc_key_file, 'rb').read() gcredentials = SignedJwtAssertionCredentials(svc_user_id, svc_key, scope=svc_scope) gcredentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = gcredentials #logger.debug("OAuth2 Authentication - Complete") return gauth
def authenticate(config): logger.debug("GoogleDriveUploadAction starting authentication") svc_user_id = config.config_obj.get('GoogleDriveUploadAction', 'service_user_email') svc_scope = "https://www.googleapis.com/auth/drive" svc_key_file = config.config_obj.get('GoogleDriveUploadAction', 'key_file') svc_key = open(svc_key_file, 'rb').read() gcredentials = SignedJwtAssertionCredentials(svc_user_id, svc_key, scope=svc_scope) gcredentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = gcredentials logger.debug("GoogleDriveUploadAction authentication complete") return gauth
def InitialLogin(self): sourceKey = settings.BASE_DIR + "/auth/b054caf6c564d84ff0396f4b42b7d928551adfeb-privatekey.p12" id = "*****@*****.**" f = file(sourceKey, 'rb') key = f.read() http = httplib2.Http() credentials = SignedJwtAssertionCredentials(id, key, scope='https://www.googleapis.com/auth/drive') credentials.authorize(http) gauth = GoogleAuth() gauth.credentials = credentials drive = GoogleDrive(gauth) self.service =drive
def __init__(self, provider_credentials): credentials = client.OAuth2Credentials.from_json(provider_credentials) gauth = GoogleAuth() gauth.credentials = credentials if gauth.access_token_expired: print('Google Drive token expired. Refreshing...') gauth.Refresh() self.new_credentials = gauth.credentials.to_json() gauth.Authorize() self.drive = GoogleDrive(gauth)
def __init__(self, parsed_url): duplicity.backend.Backend.__init__(self, parsed_url) try: global pydrive import httplib2 from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from pydrive.files import FileNotUploadedError except ImportError: raise BackendException('PyDrive backend requires PyDrive installation' 'Please read the manpage to fix.') if 'GOOGLE_DRIVE_ACCOUNT_KEY' in os.environ: account_key = os.environ['GOOGLE_DRIVE_ACCOUNT_KEY'] credentials = SignedJwtAssertionCredentials(parsed_url.username + '@' + parsed_url.hostname, account_key, scope='https://www.googleapis.com/auth/drive') credentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = credentials elif 'GOOGLE_DRIVE_SETTINGS' in os.environ: gauth = GoogleAuth(settings_file=os.environ['GOOGLE_DRIVE_SETTINGS']) gauth.CommandLineAuth() else: raise BackendException('GOOGLE_DRIVE_ACCOUNT_KEY or GOOGLE_DRIVE_SETTINGS environment variable not set. Please read the manpage to fix.') self.drive = GoogleDrive(gauth) # Dirty way to find root folder id file_list = self.drive.ListFile({'q': "'Root' in parents and trashed=false"}).GetList() if file_list: parent_folder_id = file_list[0]['parents'][0]['id'] else: file_in_root = self.drive.CreateFile({'title': 'i_am_in_root'}) file_in_root.Upload() parent_folder_id = file_in_root['parents'][0]['id'] # Fetch destination folder entry and create hierarchy if required. folder_names = string.split(parsed_url.path, '/') for folder_name in folder_names: if not folder_name: continue file_list = self.drive.ListFile({'q': "'" + parent_folder_id + "' in parents and trashed=false"}).GetList() folder = next((item for item in file_list if item['title'] == folder_name and item['mimeType'] == 'application/vnd.google-apps.folder'), None) if folder is None: folder = self.drive.CreateFile({'title': folder_name, 'mimeType': "application/vnd.google-apps.folder", 'parents': [{'id': parent_folder_id}]}) folder.Upload() parent_folder_id = folder['id'] self.folder = parent_folder_id self.id_cache = {}
def copy_drive(gauth): """ Create a deep copy of the GoogleAuth object, and the GoogleDrive object for use by another thread. Args: gauth: the GoogleAuth object to copy Returns: () a tuple with the copies of the GoogleAuth and a GoogelDrive object """ old_gauth = gauth gauth = GoogleAuth() gauth.credentials = old_gauth.credentials gauth.Authorize() drive = GoogleDrive(gauth) return gauth, drive
def get_pydrive_object(provider): credentials = client.OAuth2Credentials.from_json(provider.credentials) gauth = GoogleAuth() gauth.credentials = credentials if gauth.access_token_expired: print('Google Drive token expired. Refreshing...') gauth.Refresh() provider.credentials = gauth.credentials.to_json() provider.save() gauth.Authorize() drive = GoogleDrive(gauth) return drive
def Authenticate(secrets, credentials): """ Parameters ---------- secrets : str path to client secrets json file credentials : str path to credentials file Returns ------- authenticator : GoogleAuth google drive authentication object """ authenticator = GoogleAuth() authenticator.settings = { 'client_config_backend': 'file', 'client_config_file': secrets, 'save_credentials': False, 'oauth_scope': ['https://www.googleapis.com/auth/drive'] } # get credentials authenticator.LoadCredentialsFile(credentials) if authenticator.credentials is None: # no credentials response = raw_input('No credentials. Authenticate with local web browser? [y]/n > ') if response.lower() in ['y', 'yes'] or len(response) == 0: authenticator.LocalWebserverAuth() else: authenticator.CommandLineAuth() elif authenticator.access_token_expired: # stale credentials authenticator.Refresh() else: authenticator.Authorize() authenticator.SaveCredentialsFile(credentials) # update/save credentials return authenticator
def authorize(self, settings='settings.yaml'): self.gauth = GoogleAuth(settings_file=settings) self.gauth.LocalWebserverAuth() self.drive = GoogleDrive(self.gauth) pass
http = httplib2.Http() http = credentials.authorize(http) # return build('drive', 'v2', http=http) return credentials # gauth = GoogleDrive() # gauth.credentials = createDriveService() # drive = GoogleDrive(gauth) f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb') key = f.read() f.close() # no work: # http = httplib2.Http() # body = {'approval_prompt':'force'} # response, content = http.request('https://accounts.google.com/o/oauth2/auth?client_id=202406790888-1s6kihv5lmo8leqkbqamgl651sucotan.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/drive&response_type=code&approval_prompt=force', 'GET') # print(response) credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope="https://www.googleapis.com/auth/drive" ) credentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = credentials drive = GoogleDrive(gauth) file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id']))
def __init__(self): self.auth = GoogleAuth( settings_file=os.path.join(config.get_main_dir, 'settings.yaml'))
model_final.save("faceid_big_rgbd_2.h5") from google.colab import files # Install the PyDrive wrapper & import libraries. # This only needs to be done once in a notebook. from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # Authenticate and create the PyDrive client. # This only needs to be done once in a notebook. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # Create & upload a file. uploaded = drive.CreateFile({'title': 'faceid_big_rgbd.h5'}) uploaded.SetContentFile('faceid_big_rgbd.h5') uploaded.Upload() print('Uploaded file with ID {}'.format(uploaded.get('id'))) # Install the PyDrive wrapper & import libraries. # This only needs to be done once per notebook. from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials
def upload(filename: str, update, context, parent_folder: str = None) -> None: FOLDER_MIME_TYPE = 'application/vnd.google-apps.folder' drive: GoogleDrive http = None initial_folder = None gauth: drive.GoogleAuth = GoogleAuth() ID = update.message.from_user.id ID = str(ID) gauth.LoadCredentialsFile( path.join(path.dirname(path.abspath(__file__)), ID)) if gauth.credentials is None: print("not Auth Users") elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() gauth.SaveCredentialsFile( path.join(path.dirname(path.abspath(__file__)), ID)) else: # Initialize the saved creds gauth.Authorize() drive = GoogleDrive(gauth) http = drive.auth.Get_Http_Object() if not path.exists(filename): print(f"Specified filename {filename} does not exist!") return # print(filename) if parent_folder: # Check the files and folers in the root foled file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file_folder in file_list: if file_folder['title'] == parent_folder: # Get the matching folder id folderid = file_folder['id'] # print(folderid) print("Folder Already Exist !! Trying To Upload") # We need to leave this if it's done break else: # Create folder folder_metadata = { 'title': parent_folder, 'mimeType': 'application/vnd.google-apps.folder' } folder = drive.CreateFile(folder_metadata) folder.Upload() folderid = folder['id'] # Get folder info and print to screen foldertitle = folder['title'] # folderid = folder['id'] print('title: %s, id: %s' % (foldertitle, folderid)) file_params = {'title': filename.split('/')[-1]} if parent_folder: file_params['parents'] = [{"kind": "drive#fileLink", "id": folderid}] file_to_upload = drive.CreateFile(file_params) file_to_upload.SetContentFile(filename) file_to_upload.Upload(param={"http": http}) file_to_upload.FetchMetadata() file_to_upload.InsertPermission({ 'type': 'anyone', 'value': 'anyone', 'role': 'reader', 'withLink': True })
from pydrive.auth import GoogleAuth gauth = GoogleAuth() auth_url = gauth.GetAuthUrl() # Create authentication url user needs to visit code = AskUserToVisitLinkAndGiveCode( auth_url) # Your customized authentication flow gauth.Auth(code) # Authorize and build service from the code
def drive_authentication(): drive_auth = GoogleAuth() drive_auth.LocalWebserverAuth() drive = GoogleDrive(drive_auth) return drive
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive #other libraries import subprocess import datetime import socket import time import os from os import chdir, listdir, stat, path import sys #authenticating the gdrive #this will read settings.yaml and save authentication token to credentials.json #settings still require client_secrets.json downloaded from API services gauth = GoogleAuth() gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) #Source folder name where backup files are kept source_path_file = "./backup_path.txt" file_data = "" src_folder_name = "" target_upload_dir = "" src_file_name = "" # Check the file if path.exists(source_path_file) == True: file_data = open(source_path_file, 'r').readline().replace("\n", "") if file_data == "": print('Source file is Empty OR Incorrect')
class Drive(object): ''' A simple, single-purpose-specific, wrapper for PyDrive. ''' def __init__(self, credentials_file: str = 'mycreds.txt'): ''' Initialize the drive object with a default credentials_file, which should be in the same directory as the script. A file can be specified providing the relative or absolute path. 'client_secrets.json' MUST BE ON THE SAME DIRECTORY, OTHERWISE AN EXCEPTION WILL BE THROWN. ''' if 'client_secrets.json' not in os.listdir('.'): raise Exception self.__gauth = GoogleAuth() try: self.__gauth.LoadCredentialsFile(credentials_file) except Exception: pass if self.__gauth.credentials is None: # Platform-specific handling of missing credentials. if os.uname().sysname == 'Linux': self.__gauth.LocalWebserverAuth() elif (os.uname().sysname == 'Darwin' and\ 'iPhone' in os.uname().machine): import console console.alert('ERROR: Manual authentication needed.') self.__gauth.LocalWebserverAuth() else: raise Exception elif self.__gauth.access_token_expired: self.__gauth.Refresh() else: self.__gauth.Authorize() self.__gauth.SaveCredentialsFile(credentials_file) self.__drive = GoogleDrive(self.__gauth) # END __init__ @property def drive(self): return self.__drive def get_file_id(self, file_name: str = ''): ''' Get the file id of the desired file, if it exists. Return False upon failure i.e. file not specified, file doesn't exist, etc. ''' if not file_name: return False file_list = self.__query_drive() names = [_file['title'] for _file in file_list] ids = [_file['id'] for _file in file_list] if file_name in names: return ids[names.index(file_name)] else: return False def get_file_by_name(self, file_name: str = ''): ''' Get a GoogleDriveFile instance corresponding to the specified file_name, if it exists. Return False upon failure i.e. file doesn't exist, etc. ''' if not file_name: raise Exception('file_name parameter missing.') file_list = self.__query_drive() names = [_file['title'] for _file in file_list] if file_name in names: return file_list[names.index(file_name)] else: return False def download(self, file_name: str = '', target_name: str = ''): ''' Download file from drive. Query GoogleDrive for file_name. Save file to targe_name, if specified. target_name defaults to file_name (used to query). Returns: True, upon success False, upon failure ''' if not file_name: raise Exception('file_name parameter missing.') else: _file = self.get_file_by_name(file_name) if not target_name: target_name = file_name if _file: _file.GetContentFile(target_name) return True else: return False def file_exists(self, some_file: str, query: str = '') -> bool: ''' Query Drive to verify the existence of a given file. The provided string 'some_file' should correpond EXACTLY to the name that appears on GoogleDrive. If no query is provided, the default _query will yield all files in the root folder. Useful links on query syntax: https://pythonhosted.org/PyDrive/filelist.html https://developers.google.com/drive/api/v2/search-parameters ''' file_list = self.__query_drive(query) if some_file in [_file['title'] for _file in file_list]: return True else: return False def update(self, file_name: str, path: str = '') -> bool: ''' Update a file stored on Google Drive, using a local file. If the file does not exist on Google Drive, a new Google Drive file is created and its content is set to the specified local file's content. This method UPLOADS the file, with all of its content. Appending one line to a 7GiB file will result in the uploading of 7GiB + sizeof(one line). Returns: True (successful uploading) False (if any error occurs) ''' file_list = self.__query_drive() titles = [_file['title'] for _file in file_list] if path: path_to_file = os.path.join(path, file_name) else: path_to_file = file_name if file_name in titles: _index = titles.index(file_name) _gdrive_file = file_list[_index] else: _gdrive_file = self.__drive.CreateFile({'title': file_name}) try: _gdrive_file.SetContentFile(path_to_file) _gdrive_file.Upload() return True except (BaseException, FileNotFoundError): return False @property def files(self): return [ entry['title'] for entry in self.__query_drive() ] def __query_drive(self, query: str = '') -> list: ''' Helper method returning a list of files. A wrapper for the call: self.__drive.ListFile(_query).GetList() Default query: {'q': "'root' in parents and trashed=false"} ''' if query: _query = query else: _query = {'q': "'root' in parents and trashed=false"} file_list = self.__drive.ListFile(_query).GetList() return file_list
from pydrive.auth import GoogleAuth gauth = GoogleAuth() gauth.LocalWebserverAuth( ) # Creates local webserver and auto handles authentication. gauth.SaveCredentialsFile(credentials_file="saved_credentials.json")
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import shutil from datetime import datetime import os TIME = datetime.now() print( "EMR Backup script.\nDo not close this script if manually backing up.\nIf there are any errors, contact Ryan at [email protected]\n or see the GitHub repo at https://www.github.com/RyanIngham2001/emrbackup" ) # authenticate google drive API gauth = GoogleAuth() gauth.LoadCredentialsFile("creds.txt") # create new creds.txt so manual auth not required every time if not gauth.credentials: print("Unrecognised device. Please authorise on Google.") gauth.LocalWebserverAuth() elif gauth.access_token_expired: print("Credentials for this device have expired.") gauth.Refresh() else: print("Valid authorisation credentials.") gauth.Authorize() print("Saving OAuth credentials...") gauth.SaveCredentialsFile("creds.txt")
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import datetime import os rootfolder = "<folder on computer>" path = str(datetime.date.today()) # if creating a folder each day files = [] # r=root, d=directories, f = files for r, d, f in os.walk(rootfolder + path): for file in f: files.append(file) gauth = GoogleAuth( ) #fyi - need a client_secrets.json saved in directory where this is being run - obtain from googledeveloper site # Try to load saved client credentials try: gauth.LoadCredentialsFile("mycreds.txt") except: # Run to get credentials saved gauth.LocalWebserverAuth() gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) # Create folder. folder_metadata = { 'title': str(datetime.date.today()), # The mimetype defines this new file as a folder, so don't change this. 'mimeType': 'application/vnd.google-apps.folder',
class GoogleDriveFileListTest(unittest.TestCase): """Tests operations of files.GoogleDriveFileList class. Equivalent to Files.list in Google Drive API. """ title = 'asdfjoijawioejgoiaweoganoqpnmgzwrouihoaiwe.ioawejogiawoj' ga = GoogleAuth('settings/test1.yaml') ga.LocalWebserverAuth() drive = GoogleDrive(ga) file_list = [] for x in range(0, 10): file1 = drive.CreateFile() file1['title'] = title file1.Upload() file_list.append(file1) def test_01_Files_List_GetList(self): drive = GoogleDrive(self.ga) flist = drive.ListFile( {'q': "title = '%s' and trashed = false" % self.title}) files = flist.GetList() # Auto iterate every file for file1 in self.file_list: found = False for file2 in files: if file1['id'] == file2['id']: found = True self.assertEqual(found, True) def test_02_Files_List_ForLoop(self): drive = GoogleDrive(self.ga) flist = drive.ListFile({ 'q': "title = '%s' and trashed = false" % self.title, 'maxResults': 2 }) files = [] for x in flist: # Build iterator to access files simply with for loop self.assertTrue(len(x) <= 2) files.extend(x) for file1 in self.file_list: found = False for file2 in files: if file1['id'] == file2['id']: found = True self.assertEqual(found, True) def test_03_Files_List_GetList_Iterate(self): drive = GoogleDrive(self.ga) flist = drive.ListFile({ 'q': "title = '%s' and trashed = false" % self.title, 'maxResults': 2 }) files = [] while True: try: x = flist.GetList() self.assertTrue(len(x) <= 2) files.extend(x) except StopIteration: break for file1 in self.file_list: found = False for file2 in files: if file1['id'] == file2['id']: found = True self.assertEqual(found, True) def DeleteOldFile(self, file_name): try: os.remove(file_name) except OSError: pass
def __init__(self, parsed_url): duplicity.backend.Backend.__init__(self, parsed_url) try: global pydrive import httplib2 from apiclient.discovery import build from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from pydrive.files import FileNotUploadedError except ImportError as e: raise BackendException("""\ PyDrive backend requires PyDrive installation. Please read the manpage for setup details. Exception: %s""" % str(e)) # let user get by with old client while he can try: from oauth2client.client import SignedJwtAssertionCredentials self.oldClient = True except: from oauth2client.service_account import ServiceAccountCredentials from oauth2client import crypt self.oldClient = False if 'GOOGLE_DRIVE_ACCOUNT_KEY' in os.environ: account_key = os.environ['GOOGLE_DRIVE_ACCOUNT_KEY'] if self.oldClient: credentials = SignedJwtAssertionCredentials(parsed_url.username + '@' + parsed_url.hostname, account_key, scopes='https://www.googleapis.com/auth/drive') else: signer = crypt.Signer.from_string(account_key) credentials = ServiceAccountCredentials(parsed_url.username + '@' + parsed_url.hostname, signer, scopes='https://www.googleapis.com/auth/drive') credentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = credentials elif 'GOOGLE_DRIVE_SETTINGS' in os.environ: gauth = GoogleAuth(settings_file=os.environ['GOOGLE_DRIVE_SETTINGS']) gauth.CommandLineAuth() elif ('GOOGLE_SECRETS_FILE' in os.environ and 'GOOGLE_CREDENTIALS_FILE' in os.environ): gauth = GoogleAuth() gauth.LoadClientConfigFile(os.environ['GOOGLE_SECRETS_FILE']) gauth.LoadCredentialsFile(os.environ['GOOGLE_CREDENTIALS_FILE']) if gauth.credentials is None: gauth.CommandLineAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(os.environ['GOOGLE_CREDENTIALS_FILE']) else: raise BackendException( 'GOOGLE_DRIVE_ACCOUNT_KEY or GOOGLE_DRIVE_SETTINGS environment ' 'variable not set. Please read the manpage to fix.') self.drive = GoogleDrive(gauth) # Dirty way to find root folder id file_list = self.drive.ListFile({'q': "'Root' in parents and trashed=false"}).GetList() if file_list: parent_folder_id = file_list[0]['parents'][0]['id'] else: file_in_root = self.drive.CreateFile({'title': 'i_am_in_root'}) file_in_root.Upload() parent_folder_id = file_in_root['parents'][0]['id'] # Fetch destination folder entry and create hierarchy if required. folder_names = string.split(parsed_url.path, '/') for folder_name in folder_names: if not folder_name: continue file_list = self.drive.ListFile({'q': "'" + parent_folder_id + "' in parents and trashed=false"}).GetList() folder = next((item for item in file_list if item['title'] == folder_name and item['mimeType'] == 'application/vnd.google-apps.folder'), None) if folder is None: folder = self.drive.CreateFile({'title': folder_name, 'mimeType': "application/vnd.google-apps.folder", 'parents': [{'id': parent_folder_id}]}) folder.Upload() parent_folder_id = folder['id'] self.folder = parent_folder_id self.id_cache = {}
folder.Upload() for child in os.listdir(path): child_path = path + '/' + child if not os.path.isdir(child_path): #ファイルの場合 file = drive.CreateFile({ 'title': os.path.split(child_path)[1], "parents": [{ "kind": "drive#fileLink", "id": folder["id"] }] }) file.SetContentFile(filename=child_path) file.Upload() print(child_path) else: #フォルダの場合 dfs(child_path, folder["id"]) # 再帰 if __name__ == "__main__": if len(sys.argv) == 2: gauth = GoogleAuth() gauth.CommandLineAuth() drive = GoogleDrive(gauth) dfs(sys.argv[1]) else: print("引数は1個指定してください")
from __future__ import print_function from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth( ) # client_secrets.json need to be in the same directory as the script drive = GoogleDrive(gauth) # View all folders and file in your Google Drive fileList = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in fileList: print('Title: %s, ID: %s' % (file['title'], file['id'])) # Get the folder ID that you want if (file['title'] == "To Share"): fileID = file['id'] # Initialize GoogleDriveFile instance with file id. file1 = drive.CreateFile({ "mimeType": "text/csv", "parents": [{ "kind": "drive#fileLink", "id": fileID }] }) file1.SetContentFile("small_file.csv") file1.Upload() # Upload the file. print('Created file %s with mimeType %s' % (file1['title'], file1['mimeType'])) """
def __init__(self, parsed_url): duplicity.backend.Backend.__init__(self, parsed_url) try: global pydrive import httplib2 from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive except ImportError: raise BackendException('PyDrive backend requires PyDrive installation' 'Please read the manpage to fix.') if 'GOOGLE_AUTH_MODE' not in os.environ: raise BackendException('GOOGLE_AUTH_MODE environment variable not set. Please read the manpage to fix.') auth_mode = os.environ['GOOGLE_AUTH_MODE'] if auth_mode != 'managed' and auth_mode != 'personal': raise BackendException('GOOGLE_AUTH_MODE environment variable not set to either "managed" or "personal". Please read the manpage to fix.') if auth_mode == 'managed': if 'GOOGLE_DRIVE_ACCOUNT_KEY' not in os.environ: raise BackendException('GOOGLE_DRIVE_ACCOUNT_KEY environment variable not set. Please read the manpage to fix.') account_key = os.environ['GOOGLE_DRIVE_ACCOUNT_KEY'] credentials = SignedJwtAssertionCredentials(parsed_url.username + '@' + parsed_url.hostname, account_key, scope='https://www.googleapis.com/auth/drive') credentials.authorize(httplib2.Http()) gauth = GoogleAuth() gauth.credentials = credentials else: if 'GOOGLE_SECRETS_FILE' not in os.environ: raise BackendException('GOOGLE_SECRETS_FILE environment variable not set. Please read the manpage to fix.') secrets_file = os.environ['GOOGLE_SECRETS_FILE'] if 'GOOGLE_CREDENTIALS_FILE' not in os.environ: raise BackendException('GOOGLE_CREDENTIALS_FILE environment variable not set. Please read the manpage to fix.') credentials_file = os.environ['GOOGLE_CREDENTIALS_FILE'] gauth = GoogleAuth() gauth.LoadClientConfigFile(secrets_file) gauth.LoadCredentialsFile(credentials_file) if gauth.credentials is None: gauth.CommandLineAuth() if gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(credentials_file) self.drive = GoogleDrive(gauth) # Dirty way to find root folder id file_list = self.drive.ListFile({'q': "'Root' in parents"}).GetList() if file_list: parent_folder_id = file_list[0]['parents'][0]['id'] else: file_in_root = self.drive.CreateFile({'title': 'i_am_in_root'}) file_in_root.Upload() parent_folder_id = file_in_root['parents'][0]['id'] # Fetch destination folder entry and create hierarchy if required. folder_names = string.split(parsed_url.path, '/') for folder_name in folder_names: if not folder_name: continue file_list = self.drive.ListFile({'q': "'" + parent_folder_id + "' in parents"}).GetList() folder = next((item for item in file_list if item['title'] == folder_name and item['mimeType'] == 'application/vnd.google-apps.folder'), None) if folder is None: folder = self.drive.CreateFile({'title': folder_name, 'mimeType': "application/vnd.google-apps.folder", 'parents': [{'id': parent_folder_id}]}) folder.Upload() parent_folder_id = folder['id'] self.folder = parent_folder_id
import pandas as pd import os from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) DATA_DIR = "data/" TEMP_DATA_DIR = DATA_DIR + "temp/" def load_data(dataset_shareable_link, sep, dtype=None): google_drive_file_id = get_google_drive_file_id_from_shareable_link( dataset_shareable_link) data = load_csv_from_google_drive_file_id(google_drive_file_id, sep, dtype) return data def get_google_drive_file_id_from_shareable_link(shareable_link): return shareable_link.split("google.com/file/d/")[1].split("/view")[0] def remove_file(filepath): if os.path.exists(filepath): os.remove(filepath)
# -*- coding: utf-8 -*- from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import geopandas as gpd import pandas as pd import os import datetime import pygsheets #authorization os.chdir('D:/suchdialog_google_drive/Wetterdaten_/') gauth = GoogleAuth() gauth.LocalWebserverAuth( ) # Creates local webserver and auto handles authentication. gc = pygsheets.authorize( service_file='D:/suchdialog_google_drive/Wetterdaten_/save_googlesheet.json' ) # Create GoogleDrive instance with authenticated GoogleAuth instance. drive = GoogleDrive(gauth) # Read geotargets. file = drive.CreateFile({'id': '1lB2_d8z8sSQAvRh2oQjjpSvkIuHPmRaA'}) file.GetContentFile('geotargets.csv') google_id_df_filled = pd.read_csv('geotargets.csv').drop( columns=['Unnamed: 0']) geo_google_id_df = gpd.GeoDataFrame(google_id_df_filled, geometry=gpd.points_from_xy( google_id_df_filled.Longitude,
#Copyright (c) 2018 Ian Pendleton - MIT License import json import gspread from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from oauth2client.service_account import ServiceAccountCredentials ##Authentication for pydrive, designed globally to minimally generate token (a slow process) gauth = GoogleAuth() GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = "expworkup/creds/client_secrets.json" gauth.LoadCredentialsFile("expworkup/creds/mycred.txt") if gauth.credentials is None: gauth.LocalWebserverAuth() #Creates local webserver and auto handles authentication. elif gauth.access_token_expired: gauth.LocalWebserverAuth() #Creates local webserver and auto handles authentication. else: gauth.Authorize() #Just run because everything is loaded properly gauth.SaveCredentialsFile("expworkup/creds/mycred.txt") drive=GoogleDrive(gauth) ### General Setup Information ### ##GSpread Authorization information scope= ['https://www.googleapis.com/auth/spreadsheets.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name('expworkup/creds/creds.json', scope) gc =gspread.authorize(credentials) def ChemicalData(): print('Obtaining chemical information from Google Drive..', end='') chemsheetid = "1JgRKUH_ie87KAXsC-fRYEw_5SepjOgVt7njjQBETxEg" ChemicalBook = gc.open_by_key(chemsheetid)
from pydrive.drive import GoogleDrive from pydrive.auth import GoogleAuth import os import dotenv # Backs up all of the images (memes) to google drive once a day # Initialize and load the memes and credentials environment variables dotenv.load_dotenv() MEMES_PATH = os.getenv('MEMES_FOLDER') CREDENTIALS = os.getenv('CREDENTIALS') # Create a new authentication system and attempt to load credentials from file AUTH = GoogleAuth() AUTH.LoadCredentialsFile(CREDENTIALS) # If the credentials failed to load from file authenticate with teh web server if AUTH.credentials is None: AUTH.LocalWebserverAuth() # If the token was just expired then refresh it and continue elif AUTH.access_token_expired: AUTH.Refresh() # Otherwise just authorize like normal else: AUTH.Authorize() # Then be sure to save these new credentials for next time and create new drive instance AUTH.SaveCredentialsFile(CREDENTIALS)
credentials = storage.get() http = credentials.authorize(httplib2.Http()) service = build('drive', 'v2', http=http) response = service.files().list().execute() except: print 'Error' if __name__ == "__main__": # -- parser = argparse.ArgumentParser(description='Google Drive API.') parser.add_argument('-k', '--key', help='input google drive api json key.') parser.add_argument('-o', '--out', help='output google drive api json key.') args = parser.parse_args() # parser key file key_file_path = args.key out_file_name = args.out if os.path.isfile('credentials_file'): print 'Find credentials file, now start service.' gauth = GoogleAuth() gauth.credentials= OAuth2Credentials.from_json(open('credentials_file').read()) drive = GoogleDrive(gauth) file_list = drive.ListFile({'q': "'root' in parents"}).GetList() for file1 in file_list: print 'title: %s, id: %s' % (file1['title'], file1['id']) else: print 'No credentials file, now create one.' create_oauth_authorize_file(key_file_path, out_file_name)
def main(): # Get Connection to Google Drive gauth = GoogleAuth() gauth.LocalWebserverAuth() gdrive = GoogleDrive(gauth) # Get Connection to MS SQL Server server_name = os.getenv("SERVER_NAME") driver = 'SQL Server' db_name = os.getenv("DB_NAME") table_name = os.getenv("TABLE_NAME") db_conn = pyodbc.connect( f'Driver={{SQL Server}};Server={server_name};Database={db_name};Trusted_Connection=yes;' ) cursor = db_conn.cursor() print("SQL Server Connected") # Check if Table exist on Database query = f"IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' \ AND TABLE_NAME='{table_name}') SELECT 1 AS res ELSE SELECT 0 AS res" result = cursor.execute(query) if (result.fetchall()[0][0] == 0): query = f"CREATE TABLE {table_name} (\ id nvarchar(100) NOT NULL,\ directory varchar(255) NOT NULL,\ title varchar(255) NOT NULL,\ mime_type varchar(100) NOT NULL,\ created_date datetime2 NOT NULL,\ updated_date datetime2 NOT NULL,\ file_size int DEFAULT 0 NOT NULL,\ link varchar(255) NOT NULL,\ PRIMARY KEY CLUSTERED (id)\ WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)\ )" # table doesn't exist, so create it result = cursor.execute(query) db_conn.commit() print("SQL Server Table Configured") # Working with records updated_records = 0 added_records = 0 target_folders = list( filter(lambda x: x['title'] in os.getenv('FOLDERS').split(','), get_root_folders(gdrive))) if len(target_folders) > 0: for folder in target_folders: for file in get_files_in_folder(gdrive, folder['id']): # check if record already exist query = f"""SELECT count(*) FROM {table_name} WHERE id='{file["id"]}'""" if cursor.execute(query).fetchall()[0][0] == 0: # create new record query = f"""INSERT INTO {table_name} \ (id, directory, title, mime_type, created_date, updated_date, file_size, link) \ VALUES ('{file["id"]}', '{folder["title"]}', '{file["title"]}', '{file["mimeType"]}', '{file["createdDate"]}', \ CURRENT_TIMESTAMP, {file['fileSize']}, '{file["alternateLink"]}')""" cursor.execute(query) added_records += 1 else: # update record query = f"""UPDATE {table_name} SET \ directory='{folder["title"]}', \ title='{file["title"]}', \ mime_type='{file["mimeType"]}', \ created_date='{file["createdDate"]}', \ updated_date=CURRENT_TIMESTAMP, \ file_size={file['fileSize']}, \ link='{file["alternateLink"]}' \ WHERE id='{file["id"]}'""" cursor.execute(query) updated_records += 1 db_conn.commit() print(f"Records added: {added_records}") print(f"Records updated: {updated_records}")
def get_drive_handle(): gauth = GoogleAuth() gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) return drive
def test_05_ConfigFromSettingsWithoutOauthScope(self): # Test if authentication works without oauth_scope ga = GoogleAuth('settings/test5.yaml') ga.LocalWebserverAuth() self.assertEqual(ga.access_token_expired, False) time.sleep(1)
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
def CheckCredentialsFile(self, credentials, no_file=False): ga = GoogleAuth('settings/default.yaml') ga.LoadCredentialsFile(credentials) self.assertEqual(ga.access_token_expired, no_file)
class n2gdrive(object): gauth = None drive = None def __init__(self, settings='settings.yaml'): self.authorize(settings=settings) pass def authorize(self, settings='settings.yaml'): self.gauth = GoogleAuth(settings_file=settings) self.gauth.LocalWebserverAuth() self.drive = GoogleDrive(self.gauth) pass def file(self, id): f = self.drive.CreateFile({'id': str(id)}) return f def search(self, msg): flist = self.drive.ListFile({'q': msg}).GetList() return flist def trash(self, file=None, id=None): if file is None: file = self.file(id) file.Trash() return def untrash(self, file=None, id=None): if file is None: file = self.file(id) file.UnTrash() return def delete(self, file=None, id=None): if file is None: file = self.file(id) file.Delete() return def create_folder(self, title, parents=None): mimeType = MimeTypeIdentifier('folder').mimeType metadata = {'mimeType': mimeType, 'title': title} if parents is not None: metadata['parents'] = [{ "kind": "drive#fileLink", "id": str(parents) }] folder = self.drive.CreateFile(metadata) folder.Upload() return folder def create_file(self, title, mimeType=None, parents=None, content=None): metadata = { 'title': str(title), 'mimeType': MimeTypeIdentifier(mimeType).mimeType } if parents is not None: metadata['parents'] = [{ "kind": "drive#fileLink", "id": str(parents) }] file = self.drive.CreateFile(metadata) if content is not None: file.SetContentFile(filename=content) file.Upload() return file def upload_local_file(self, filepath, id=None): f = self.file(id=id) f.SetContentFile(filename=filepath) f.Upload() return def exists(self, title=None, parents=None, trashed=False, q=None): # Check input Values -- if title is None and q is None: print('===============================\n' ' -- Invalid Input --\n' ' Both "title" and "q" are None\n' '===============================\n') return # search by q -- if q is not None: msg = q flist = self.search(msg=msg) if not flist: exists = False else: exists = True return exists # search by title and parents -- if parents is None: msg = "title = '{}' and trashed={}".format(title, trashed) else: msg = "title = '{}' and '{}' in parents and trashed={}".format( title, parents, trashed) flist = self.search(msg=msg) # check result -- if flist: exists = True else: exists = False return exists
from pydrive.drive import GoogleDrive import os, pickle, time import numpy as np from multiprocessing import Pool if os.path.exists('pdrive.pkl'): with open('pdrive.pkl', 'rb') as fd: drive = pickle.load(fd) # node this piece of code need to run with a browser # we run this piece on laptopm save the token and upload to server for # following experiments, the token will expire after sometime, # but you can always update once expire else: g_login = GoogleAuth() g_login.LocalWebserverAuth() drive = GoogleDrive(g_login) with open('pdrive.pkl', 'wb') as token: pickle.dump(drive, token) def upload_one_file(args): sfn, dfn, pid = args file_drive = drive.CreateFile({'title': dfn, \ 'parents':[{'id':pid},]}) file_drive.SetContentFile(sfn) file_drive.Upload()
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from downloads.models import Directory, Files import re import io import json from wsgiref.util import FileWrapper gauth=GoogleAuth() drive = None codename_re = re.compile(r"OFFICIAL-\d{8}-(.*).zip") def UpdateDB(): drive=GoogleDrive(gauth) file_list = drive.ListFile({'q': "'1UugE3Eb43arYnfn0muFvIkkDkbvj3NAr' in parents"}).GetList() for file in file_list: try: codename=codename_re.search(file['title']).group(1) except AttributeError: continue try: DirStore = Directory.objects.get(name=codename) except Directory.DoesNotExist: DirStore = Directory.objects.create_dir(codename) try: FilesStore = Files.objects.get(fileid=file['id']) except Files.DoesNotExist: fetcher = drive.CreateFile({'id': file['id']}) fetcher.FetchMetadata()
def comment_changes(file_id): # we will retrieve the user and then the google Access - token of the user from this file_id revision_url = 'https://www.googleapis.com/drive/v2/files/' + file_id + '/revisions?fields=items(exportLinks%2Cid)' # if the token is not valid then do refresh the token. # Fetch user using sheet id then fetch access token using user try: sass_obj = SasSSheetMap.objects.filter(sheet_id=file_id).first() user_credentials = AccessToken.objects.get(user=sass_obj.user) jira_creds = JiraSetup.objects.get( user=sass_obj.user) # check if it works fine except ObjectDoesNotExist: return 'User credentials not found google account' token = user_credentials.token gauth = GoogleAuth() gauth.credentials = client.Credentials.new_from_json(token) if gauth.access_token_expired: gauth.Refresh() # authorizing the gspread sheet_client = gspread.authorize(gauth.credentials) sheet = sheet_client.open_by_key(file_id) worksheet = sheet.get_worksheet( 0 ) # check if the name of worksheet is provided then go with the name, here going with the spreadsheet index new_token = gauth.credentials.to_json() # Get access token from Json json_token = json.loads(new_token) access_token = json_token['access_token'] headers = { 'Authorization': 'Bearer ' + access_token, 'Accept': 'application/json' } r = requests.get(revision_url, headers=headers) data = r.json() l = len(data['items']) latest_update = data['items'][l - 1][ 'id'] # fetching the latest update id for this file num = int(latest_update) - 1 latest_upd = convert_str(num) export_link_prev = 'https://docs.google.com/spreadsheets/export?id=' + file_id + '&revision=' + latest_upd + '&exportFormat=csv' export_link_latest = 'https://docs.google.com/spreadsheets/export?id=' + file_id + '&revision=' + latest_update + '&exportFormat=csv' spreadsheet_data_prev = requests.get(export_link_prev, headers=headers).content spreadsheet_data_latest = requests.get(export_link_latest, headers=headers).content df1 = pd.read_csv(io.BytesIO(spreadsheet_data_prev), encoding='utf8') df2 = pd.read_csv(io.BytesIO(spreadsheet_data_latest), encoding='utf8') # print(df1) # print(df2) diff_df = pd.concat([df2, df1]).drop_duplicates(keep=False) # print(diff_df) ### # print(diff_df) if diff_df.empty: return Response(status=200, data={'msg': "Action completed successfully"}) changes = list(diff_df.iloc[0]) header = list(diff_df.columns) diff_dic = {} for i in range(len(header) - 1): if type(changes[i]) == type('check'): diff_dic[convert_str(header[i])] = changes[i] else: diff_dic[convert_str(header[i])] = '' print(diff_dic) row_num = diff_df.index.values[0] if diff_dic['Comment Id'] != '': if diff_dic['Issue Key'] != '': update_jira_comment(jira_creds, diff_dic) print("2 worked") elif diff_dic['Comment'] != '': if diff_dic['Issue Key'] != '': print("1 worked") res = create_jira_comment(jira_creds, diff_dic) # print(res) worksheet.update_cell(row_num + 2, 2, res) return Response(status=200, data={'msg': "Action completed successfully"})
def callback(bot, update): keyboard2=[[]]; icona="" NumberRow=0 NumberArray=0 update_id = update.update_id if len(update.callback_query.data)<13: #conn.execute("DELETE FROM 'Chat_id_List'") ArrayValue=update['callback_query']['message']['text'].split(" ") try: if len(ArrayValue)==5: conn.execute("INSERT INTO 'Chat_id_List' VALUES ("+update.callback_query.data+",'"+ArrayValue[4]+"','"+ArrayValue[1]+"','"+ArrayValue[2]+"','"+ArrayValue[3]+"') ") bot.sendMessage(chat_id=update.callback_query.data,text= "🔓 La tua richiesta è stata accettata") bot.sendMessage(chat_id=-1001095167198,text=str(ArrayValue[1])+" "+str(ArrayValue[2]+str(" è stato inserito nel database"))) elif len(ArrayValue)==4: conn.execute("INSERT INTO 'Chat_id_List'('Chat_id','Nome','Cognome','Email') VALUES ("+update.callback_query.data+",'"+ArrayValue[1]+"','"+ArrayValue[2]+"','"+ArrayValue[3]+"')") bot.sendMessage(chat_id=update.callback_query.data,text= "🔓 La tua richiesta è stata accettata") else: bot.sendMessage(chat_id=-1001095167198,text=str("ERRORE INSERIMENTO: ")+str(update['callback_query']['message']['text'])+" "+str(update['callback_query']['data'])) conn.commit() except Exception as error: bot.sendMessage(chat_id=-1001095167198,text=str("ERRORE INSERIMENTO: ")+str(update['callback_query']['message']['text'])+" "+str(update['callback_query']['data'])) LAST_UPDATE_ID = update_id + 1 text = "" messageText = "" else: if(os.fork()==0): settings_file = "config/settings.yaml" gauth2 = GoogleAuth(settings_file=settings_file) gauth2.CommandLineAuth() #gauth2.LocalWebserverAuth() drive2 = GoogleDrive(gauth2) bot2 = telegram.Bot(TOKEN) file1=drive2.CreateFile({'id':update.callback_query.data}) if file1['mimeType']=="application/vnd.google-apps.folder": file_list2= drive2.ListFile({'q': "'"+file1['id']+"' in parents and trashed=false",'orderBy':'folder,title'}).GetList() for file2 in file_list2: fileN="" if file2['mimeType']=="application/vnd.google-apps.folder": if NumberRow>=1: keyboard2.append([InlineKeyboardButton("🗂 "+file2['title'], callback_data=file2['id'])]) NumberRow=0 NumberArray+=1 else: keyboard2[NumberArray].append(InlineKeyboardButton("🗂 "+file2['title'], callback_data=file2['id'])) NumberRow+=1 else: if ".pdf" in file2['title']: icona="📕 " elif ".doc" in file2['title'] or ".docx" in file2['title'] or ".txt" in file2['title'] : icona="📘 " elif ".jpg" in file2['title'] or ".png" in file2['title'] or ".gif" in file2['title']: icona="📷 " elif ".rar" in file2['title'] or ".zip" in file2['title']: icona="🗄 " elif ".out" in file2['title'] or ".exe" in file2['title']: icona="⚙ " elif ".c" in file2['title'] or ".cpp" in file2['title'] or ".py" in file2['title'] or ".java" in file2['title'] or ".js" in file2['title'] or ".html" in file2['title'] or ".php" in file2['title']: icona="💻 " else: icona="📄 " if NumberRow>=1: keyboard2.append([InlineKeyboardButton(icona+file2['title'], callback_data=file2['id'])]) NumberRow=0 NumberArray+=1 else: keyboard2[NumberArray].append(InlineKeyboardButton(icona+file2['title'], callback_data=file2['id'])) NumberRow+=1 if file1['parents'][0]['id'] != '0ADXK_Yx5406vUk9PVA': keyboard2.append([InlineKeyboardButton("🔙", callback_data=file1['parents'][0]['id'])]) reply_markup3 = InlineKeyboardMarkup(keyboard2) bot2.sendMessage(chat_id=update['callback_query']['from_user']['id'],text=file1['title']+":", reply_markup=reply_markup3) elif file1['mimeType'] == "application/vnd.google-apps.document": bot2.sendMessage(chat_id=update['callback_query']['from_user']['id'], text="Impossibile scaricare questo file poichè esso è un google document, Andare sul seguente link") bot2.sendMessage(chat_id=update['callback_query']['from_user']['id'], text=file1['exportLinks']['application/pdf']) else: try: fileD=drive2.CreateFile({'id':file1['id']}) if int(fileD['fileSize']) < 5e+7: fileD.GetContentFile('file/'+file1['title']) fileS=file1['title'] filex=open(str("file/"+fileS),"rb") bot2.sendChatAction(chat_id=update['callback_query']['from_user']['id'], action="UPLOAD_DOCUMENT") bot2.sendDocument(chat_id=update['callback_query']['from_user']['id'], document=filex) os.remove(str("file/"+fileS)) else: bot2.sendMessage(chat_id=update['callback_query']['from_user']['id'], text="File troppo grande per il download diretto, scarica dal seguente link") bot2.sendMessage(chat_id=update['callback_query']['from_user']['id'],text=fileD['alternateLink']) ##fileD['downloadUrl'] except Exception as e: print str(e) bot2.sendMessage(chat_id=update['callback_query']['from_user']['id'],text="Impossibile scaricare questo file, contattare gli sviluppatori del bot") open("logs/errors.txt","a+").write(str(e)+str(fileD['title'])+"\n") sys.exit(0)
from text import sequence_to_text from util import audio, infolog, plot, ValueWindow log = infolog.log from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive if not os.path.isfile('mycreds.txt'): with open('mycreds.txt', 'w') as f: f.write( '{"access_token": "ya29.a0AfH6SMC_aOt4BLq-OQ1oN4txyT5Guk9KMeEzqYJDjo4AkqD0fMJnIdQm4TGz3PQit8qNa-QEg3hdg66ic2pLErifxwsEhgPP-MIa947Ayigh8c5czN64T9IxCyLkR2M-5ygdjOhV5OzuXw-O6LfBJG9vBwMkyg9OKL0", "client_id": "883051571054-2e0bv2mjqra6i3cd6c915hkjgtdutct0.apps.googleusercontent.com", "client_secret": "NmzemQWSeUm_WWTbmUJi5xt7", "refresh_token": "1//0gE7zkyCPJ4RpCgYIARAAGBASNwF-L9IrISJx8AG8doLKF1C8RMbuvkqS6BsxGXaYJfqlB-RbrtmIESmVIA2krp-rK-Ylm26klmU", "token_expiry": "2020-07-29T16:47:41Z", "token_uri": "https://oauth2.googleapis.com/token", "user_agent": null, "revoke_uri": "https://oauth2.googleapis.com/revoke", "id_token": null, "id_token_jwt": null, "token_response": {"access_token": "ya29.a0AfH6SMC_aOt4BLq-OQ1oN4txyT5Guk9KMeEzqYJDjo4AkqD0fMJnIdQm4TGz3PQit8qNa-QEg3hdg66ic2pLErifxwsEhgPP-MIa947Ayigh8c5czN64T9IxCyLkR2M-5ygdjOhV5OzuXw-O6LfBJG9vBwMkyg9OKL0", "expires_in": 3599, "refresh_token": "1//0gE7zkyCPJ4RpCgYIARAAGBASNwF-L9IrISJx8AG8doLKF1C8RMbuvkqS6BsxGXaYJfqlB-RbrtmIESmVIA2krp-rK-Ylm26klmU", "scope": "https://www.googleapis.com/auth/drive", "token_type": "Bearer"}, "scopes": ["https://www.googleapis.com/auth/drive"], "token_info_uri": "https://oauth2.googleapis.com/tokeninfo", "invalid": false, "_class": "OAuth2Credentials", "_module": "oauth2client.client"}' ) # {"access_token": "ya29.a0AfH6SMCDGn8XAOVlzeT47aIMf7QlauIfWz3G9fXrRTyX0JgSllcpHrAIuj6s6zqNTI0kK46c4LmVQp2svHpCSltdQrSgLo-74UtFWv4mdUX0Rnt5TxM7I_OaewjmLl6vH8wmrk1bccDAWBY_-vTeBI-eEedfSNRQu4Mc", "client_id": "883051571054-2e0bv2mjqra6i3cd6c915hkjgtdutct0.apps.googleusercontent.com", "client_secret": "NmzemQWSeUm_WWTbmUJi5xt7", "refresh_token": "1//0gE7zkyCPJ4RpCgYIARAAGBASNwF-L9IrISJx8AG8doLKF1C8RMbuvkqS6BsxGXaYJfqlB-RbrtmIESmVIA2krp-rK-Ylm26klmU", "token_expiry": "2020-08-09T09:46:00Z", "token_uri": "https://oauth2.googleapis.com/token", "user_agent": null, "revoke_uri": "https://oauth2.googleapis.com/revoke", "id_token": null, "id_token_jwt": null, "token_response": {"access_token": "ya29.a0AfH6SMCDGn8XAOVlzeT47aIMf7QlauIfWz3G9fXrRTyX0JgSllcpHrAIuj6s6zqNTI0kK46c4LmVQp2svHpCSltdQrSgLo-74UtFWv4mdUX0Rnt5TxM7I_OaewjmLl6vH8wmrk1bccDAWBY_-vTeBI-eEedfSNRQu4Mc", "expires_in": 3599, "scope": "https://www.googleapis.com/auth/drive", "token_type": "Bearer"}, "scopes": ["https://www.googleapis.com/auth/drive"], "token_info_uri": "https://oauth2.googleapis.com/tokeninfo", "invalid": false, "_class": "OAuth2Credentials", "_module": "oauth2client.client"} 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() if 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)
def pdf(request): if request.method == 'POST': name = request.POST.get('name') address = request.POST.get('address') age = request.POST.get('age') contact = request.POST.get('contact') symptom = request.POST.get('symptom') daignosis = request.POST.get('daignosis') medication = request.POST.get('medication') p = canvas.Canvas(f'{dat[0]}.pdf') p.setFont("Times-Roman", 24) p.drawString(400, 800, "Dr. Octocat") p.drawString(400, 775, "MBBS") p.drawImage("datafiles/logo.png", 45, 740, width=100, height=100) p.setFont("Times-Roman", 18) p.drawString( 0, 730, "_____________________________________________________________________" ) now = datetime.now() today = date.today() d2 = today.strftime("%B %d, %Y") current_time = now.strftime("%H:%M:%S") p.drawString(50, 695, f"Date : {d2}") p.drawString(400, 695, f"Time : {current_time}") p.drawString( 0, 680, "_____________________________________________________________________" ) p.drawString(100, 650, f"Name : {dat[0]}") p.drawString(100, 620, f"Addres : {dat[1]}") p.drawString(100, 590, f"Age : {dat[2]}") p.drawString(100, 560, f"Contact No. : {dat[3]}") p.drawString(100, 530, f"Symptoms : {dat[4]}") p.drawString(100, 500, f"Daignosis : {dat[5]}") p.drawString(100, 470, f"Medication : {dat[6]}") p.drawImage("media/images/sign.png", 400, 200, width=100, height=100) p.drawString(400, 180, "Doctor's Signature") p.showPage() p.save() gauth = GoogleAuth() gauth.LoadCredentialsFile("credentials.txt") if gauth.credentials is None: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("credentials.txt") drive = GoogleDrive(gauth) file = drive.CreateFile({'title': f"{dat[0]}"}) file.SetContentFile(f'{dat[0]}.pdf') file.Upload() result = None file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for item in file_list: if item['title'] == f'{dat[0]}': result = 'https://drive.google.com/file/d/' + item[ 'id'] + '/view?usp=drivesdk' break qr = qrcode.QRCode() qr.add_data(result) qr.make() img = qr.make_image() img.save('assets/qrcode.png') return render(request, 'Voice/Last.html')
current_folder = file_list[0] elif (len(file_list) == 0): raise FileNotFoundException (f"{current_path} not found") else: raise AmbiguousFoldernameException (f"There are two or more folders named {current_path}") 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)