A python Google Drive API v3 wrapper that enables:
- Uploading of files to Google Drive
- Listing of all files & folders available to a service account.
- Sharing of files with a list of email addresses.
How To Use
1. Install the module using pip:pip install googledrivepython
-
Import the module & instantiate the GoogleDrivePython class:
import googledrivepython as gdp gdrive = gdp.GoogleDrivePython() -
Store the full path to your google service account in a variable:
service_account = '/Users/luyanda.dhlamini/Projects/client_secret.json' -
Create service account credentials:
# Create credentials using the create_credentials function credentials = gdrive.create_credentials(service_account_json_filename = service_account) # Overwrite the class's default credentials with the newly created credentials. gdrive.credentials = credentials
-
Create a test text file for demonstration purposes:
# Create & save a text file into the local directory test_file = "test_file.txt" f = open(test_file, "w") f.write("This will be written to text file.") f.close()
-
Upload the text file created above to google drive:
# The code below would be used if we wanted to upload the file to an exsting google drive folder. # parent_folder_id would be passed in as an argument into the upload_file_to_google_drive() function using the 'parent_id' argument. # parent_folder_id = '1czCX8xlhkPyxuDl3gnUbEqncVO000000' # Upload the text file created above to google drive, storing its file_id in a dictionary file_id_dict = gdrive.upload_file_to_google_drive(path=test_file) # View the returned file id info. print(file_id_dict) # Get the id from the newly created file dictionary object file_id = file_id_dict['id']
-
Share the newly uploaded file with a list of email addresses. Give each recipient a role.
# Write down the email address(es) to share the file with in a list. email_list = ['johnsmith@gmail.com', 'luyendedlamini@gmail.com', 'rajarsheem@gmail.com'] # Share the file with the email address list & print out the returned dictionary. share_results = gdrive.share_google_drive_file(file_id=file_id, emails=email_list) print(share_results)
-
View the 100 most recently created files & folders for the service account to check if the test_file.txt is there.
# Get all files & folders available to the service account into a dictionary. all_files_dict = gdrive.list_files_in_google_drive() # Print & view the available file, folder names and ids. # The newly created text file should also appear in the output. print(all_files_dict)