Getting Started

Credentials Google Drive API


Create a Project in Google Cloud Console:

  • Go to the Google Cloud Console.
  • Click on "Select a project" at the top left corner and then click on "New Project".
  • Give your project a name and click "Create".


  • Enable Google Drive API:

  • In the Google Cloud Console, navigate to the "APIs & Services" > "Library" section.
  • Search for "Google Drive API" and click on it.
  • Click the "Enable" button.


  • Create Credentials:

  • After enabling the API, go to "APIs & Services" > "Credentials".
  • Click on "Create credentials" and select "OAuth client ID".
  • Choose the application type as "Desktop app" or "Other" depending on your use case.
  • Give your OAuth client a name.
  • Click on "Create". This will download a JSON file containing your credentials.


  • Download Credentials JSON:

  • Once you've created the OAuth client ID, you will be redirected to the credentials page.
  • Find the newly created credentials under "OAuth 2.0 Client IDs" and click on the download icon to download the JSON file.


  • Installation

    Install Use Pypi

    pip install DriveX



    Install Use Github

    git clone https://github.com/Sepehr0Day/DriveX.git




    Connect To Google Drive

    Normally, when you want to communicate with Google Drive, you need to singin every time.
    But by using this library, you only need Singin once!


    Code:

    
    from DriveX import ServiceBuilder, GoogleDriveAPI
    
    credentials_path = 'credentials.json' # credentials you get from Google Drive API
    token_path = 'Resources/Authenticator' # Address save token path
    token_name = 'token' # Name you want token saved
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) # Create Service
      
    try:
        drive_service = service_builder.build_service() # Build service
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path) # Connect to Google Drive API
        print("You Successfully Connected To Your Google Drive Account!")     
    except Exception as e:
        print(f"An error occurred: {e}")
    

    Output:

    
    You Successfully Connected To Your Google Drive Account!
                


    Class GoogleDriveAPI

    Functions


    list_files

    Code:

    
    from DriveX import ServiceBuilder, GoogleDriveAPI, FolderError, FileError
    
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator' 
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
                  
    try:
        drive_service = service_builder.build_service()
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path) 
        print("Listing files in Google Drive:")
        files = drive_api.list_files()  # List all files in Google Drive
                  
        for file in files:
            # Print file name, permissions, and ID
            print(f"File Name: {file['name']}, Permissions: {file['permissions']} , File ID : {file['id']}\n")  
    
    except FolderError as e:
      print(f"Folder error occurred: {e}") 
    except FileError as e:
      print(f"File error occurred: {e}")  
    except Exception as e:
      print(f"An error occurred: {e}")  
                

    Output:

    
    Listing files in Google Drive:
    
    File Name: Test Folder, Permissions: Role: owner, Email: user@gmail.com,        
    File ID : 1FCM59BxxplM3qbyOQrl8IszAKaEeZvHX, Create Time : 2024-03-03T18:27:50.497Z   
    
    File Name: file.txt, Permissions: Role: owner, Email: user@gmail.com,
    File ID : 1ugsYYW8srvnSNMRCxkVOyPPsxLKoBXSU, Create Time : 2024-03-03T18:42:50.244Z   
                            
                            

    get_file_info

    Code:

    
    from DriveX import ServiceBuilder, GoogleDriveAPI, FolderError, FileError
    
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator' 
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
                  
    try:
        drive_service = service_builder.build_service()
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path)
        print("Get Info FIle From Google Drive:")
        file = drive_api.get_file_info(file_id="1ugsYYW8srvnSNMRCxkVOyPPsxLKoBXSU")
        print(file)
    
    except FolderError as e:
      print(f"Folder error occurred: {e}") 
    except FileError as e:
      print(f"File error occurred: {e}")  
    except Exception as e:
      print(f"An error occurred: {e}")  
                

    Output:

    
    Get Info FIle From Google Drive:
    {'kind': 'drive#file', 'id': '1ugsYYW8srvnSNMRCxkVOyPPsxLKoBXSU', 'name': 'file.txt', 'mimeType': 'text/plain'}
                            
                            


    Class FileManager

    Functions


    upload_file

    Code:

    
    from DriveX import (
        ServiceBuilder,
        GoogleDriveAPI,
        FileManager,
        NetworkError, 
        FileError)
              
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator'
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
    try:
        drive_service = service_builder.build_service() 
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path)
        file_manager = FileManager(service=drive_service)
        uploaded_file_id = file_manager.upload_file('file.txt')
        print("Uploaded File ID:", uploaded_file_id)
    except NetworkError as e:
        print(f"Network Error: {e}")
    except FileError as e:
        print(f"File error occurred: {e}")
    except Exception as e:
        print(f"An error occurred: {e}") 
              
              

    Output:

    
    Uploaded File ID: 1Kh0mE0iIaZiBHp-sev7AScWuaurrlQNm
                          


    download_file

    Code:

    
    from DriveX import (
        ServiceBuilder,
        GoogleDriveAPI,
        FileManager,
        NetworkError, 
        FileError)
              
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator'
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
    try:
        drive_service = service_builder.build_service() 
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path)
        file_manager = FileManager(service=drive_service)
        file_manager.download_file("1Kh0mE0iIaZiBHp-sev7AScWuaurrlQNm", 'FileTxt.txt')
        print("File downloaded successfully.")
    except NetworkError as e:
        print(f"Network Error: {e}")
    except FileError as e:
        print(f"File error occurred: {e}")
    except Exception as e:
        print(f"An error occurred: {e}") 
              
              

    Output:

    
    File downloaded successfully.
    


    read_file

    Code:

    
    from DriveX import (
        ServiceBuilder,
        GoogleDriveAPI,
        FileManager,
        NetworkError, 
        FileError)
              
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator'
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
    try:
        drive_service = service_builder.build_service() 
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path)
        file_manager = FileManager(service=drive_service)
        data_file = file_manager.read_file("1Kh0mE0iIaZiBHp-sev7AScWuaurrlQNm")
        print("Data File : " + data_file)
    except NetworkError as e:
        print(f"Network Error: {e}")
    except FileError as e:
        print(f"File error occurred: {e}")
    except Exception as e:
        print(f"An error occurred: {e}") 
              
              

    Output:

    
    Data File : Hello From DriveX!
                        


    delete_file

    Code:

    
    from DriveX import (
        ServiceBuilder,
        GoogleDriveAPI,
        FileManager,
        NetworkError, 
        FileError)
              
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator'
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
    try:
        drive_service = service_builder.build_service() 
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path)
        file_manager = FileManager(service=drive_service)
        file_id = "1Kh0mE0iIaZiBHp-sev7AScWuaurrlQNm"
        data_file = file_manager.delete_file(file_id)
        print(f"File With Id ({file_id}) Deleted")
    except NetworkError as e:
        print(f"Network Error: {e}")
    except FileError as e:
        print(f"File error occurred: {e}")
    except Exception as e:
        print(f"An error occurred: {e}") 
              

    Output:

    
    File With Id (1Kh0mE0iIaZiBHp-sev7AScWuaurrlQNm) Deleted
    


    copy_file

    Code:

    
    from DriveX import (
        ServiceBuilder,
        GoogleDriveAPI,
        FileManager,
        FolderManager,
        NetworkError, 
        FileError)
              
    credentials_path = 'credentials.json' 
    token_path = 'Resources/Authenticator'
    token_name = 'token'
    service_builder = ServiceBuilder(credentials_path=credentials_path, token_path=token_path, token_name=token_name) 
    try:
        drive_service = service_builder.build_service() 
        drive_api = GoogleDriveAPI(service=drive_service, credentials=credentials_path)
        file_manager = FileManager(service=drive_service)
        folder_manager = FolderManager(service=drive_service)
        
        folder_id = folder_manager.create_folder('Test Folder')
        print("New Folder ID:", folder_id)
        copied_file_id = file_manager.copy_file(file_id="1ugsYYW8srvnSNMRCxkVOyPPsxLKoBXSU", new_parent_id=folder_id)
        print("Copied File ID:", copied_file_id)
    except NetworkError as e:
        print(f"Network Error: {e}")
    except FileError as e:
        print(f"File error occurred: {e}")
    except Exception as e:
        print(f"An error occurred: {e}") 
              

    Output:

    
    New Folder ID: 1fpP0Xr0rQIKDzRqqbVhvLwPE_gXT_mnU
    Copied File ID: 1BWe_YBO6lk2O4BFDdZmLPylxIm5noANb
    


    Issues

    If you have any issue please raise a PR in github