Skip to main content

A Python library for interacting with Google Drive and Google Sheets.

Project description

:snake: Gdrive-Suite

Python Version License PyPi Version MIT License

GDrive Suite is a robust Python library designed to streamline interaction with Google Drive and Google Sheets. It provides an intuitive, high-level interface over the official Google APIs, handling authentication, token management, and API calls so you can focus on your data workflows.

Whether you're a data engineer building ETL pipelines, a data analyst fetching the latest reports, or a data scientist accessing datasets, GDrive Suite simplifies cloud file management.

Features

Seamless Authentication: Handles OAuth2 flow and token refreshing automatically, supporting both local and server environments (via Application Default Credentials).

File Operations: Easily download, upload, and list files and folders.

Google Workspace Conversion: Automatically convert Google Docs, Sheets, and Slides to formats like .docx, .xlsx, and .pdf on download.

Path-Based Navigation: Find files and folders using familiar directory paths (e.g., reports/2025/monthly).

Direct Data Retrieval: Pull data directly from Google Sheets into your Python environment.

In-Memory File Handling: Retrieve file content directly into a BytesIO object for in-memoryprocessing without writing to disk.

:package: Installation

Install gdrive-suite directly from Pypi.

pip install gdrive-suite

The library requires python 3.11 or higher.

:hammer_and_wrench: Configuration

To use GDrive Suite, you need to enable the Google Drive API and obtain credentials for your application.

  1. Enable the Google Drive API
  • Go to the Google Cloud Console.

  • Create a new project or select an existing one.

  • In the navigation menu, go to APIs & Services > Library.

  • Search for "Google Drive API" and "Google Sheets API" and enable both.

  1. Create Credentials
  • In the navigation menu, go to APIs & Services > Credentials.

  • Click Create Credentials > OAuth client ID.

  • Select Desktop app as the application type.

  • Give the client ID a name (e.g., "GDrive Suite Client") and click Create.

  • A window will appear. Click Download JSON to download the credentials file.

  1. Set Up Your Project
  • Rename the downloaded JSON file to google_credentials.json.

  • In your project, create a directory to store this file. We recommend conf/local.

  • Place the google_credentials.json file in this directory.

Your project structure should look like this:o use Gdrive Suite you need to enable

- Place credentials in `conf/local`

```bash
├── conf
│   └── local       ├── credentials.json
├── src
│   ├── script.py

The first time you run your application, you will be prompted to authorize it via a browser window. A google_token.json file will then be created in the same directory. This token will be automatically refreshed as needed.

Usage Examples

Basic Usage: Download a file

This example shows how to initialize the client and download a file.

from pathlib import Path
from gdrive_suite import GDriveClient, GDriveClientConfig

# --- 1. Configuration ---
# Define the path to your configuration directory
CONFIG_DIR = Path("conf/local")

# Define the required API scopes
# .readonly is safer if you only need to read files
GOOGLE_SCOPES = [
    ["https://www.googleapis.com/auth/drive.readonly, https://www.googleapis.com/auth/drive.file"]
    # Needed for uploads/modifications
]

# --- 2. Initialization ---
# Create a configuration object
gdrive_config = GDriveClientConfig(
    config_dir_path=CONFIG_DIR,
    scope=GOOGLE_SCOPES,
)

# Create the GDriveClient instance
gdrive_client = GDriveClient(gdrive_config)

# --- 3. Download a file ---
# Specify the directory to download the file to
download_dir = Path("downloads")
download_dir.mkdir(exist_ok=True)

# The unique ID of the file from its Google Drive URL
file_id = "YOUR_FILE_ID" # Replace with the actual file ID
file_name = "my_downloaded_report.csv"

print(f"Downloading '{file_name}'...")
gdrive_client.download_file(
    directory_path=download_dir,
    file_id=file_id,
    file_name=file_name,
)
print(f"File successfully downloaded to '{download_dir}'")

Data Professional Workflow: Load a Google Sheet into Pandas

A common task for data analysts is to pull the latest version of a report from Google Drive. This example shows how to find a Google Sheet by its path and load its contents directly into a pandas DataFrame.

import pandas as pd
from pathlib import Path
from gdrive_suite import GDriveClient, GDriveClientConfig

# --- Initialization (same as above) ---
CONFIG_DIR = Path("conf/local")
GOOGLE_SCOPES = [
    ["https://www.googleapis.com/auth/drive.readonly, https://www.googleapis.com/auth/drive.file"]
]
gdrive_config = GDriveClientConfig(CONFIG_DIR, GOOGLE_SCOPES)
gdrive_client = GDriveClient(gdrive_config)

# --- Find and load the sheet ---
try:
    # Find the folder ID by navigating from the root ('root')
    # This is more robust than hardcoding folder IDs
    folder_path = ["Sales Reports", "2025", "Q3"]
    target_folder_id = gdrive_client.find_folder_id_by_path(
        start_folder_id="root",
        path_segments=folder_path
    )

    if target_folder_id:
        # Now, list files in that folder to find our report
        query = f"'{target_folder_id}' in parents and name='Q3 Sales Summary'"
        files = gdrive_client.list_files(query)

        if files:
            sheet_file = files[0]
            print(f"Found file: {sheet_file['name']} (ID: {sheet_file['id']})")

            # Retrieve the data from the first sheet (tab)
            sheet_data = gdrive_client.retrieve_sheet_data(
                spreadsheet_id=sheet_file['id'],
                sheet_range="Sheet1" # Reads the entire sheet
            )

            if sheet_data:
                # Convert to a pandas DataFrame
                df = pd.DataFrame(sheet_data[1:], columns=sheet_data[0])
                print("\nSuccessfully loaded data into DataFrame:")
                print(df.head())
            else:
                print("Sheet contains no data.")
        else:
            print("Could not find the specified file in the target folder.")

except (IOError, ValueError) as e:
    print(f"An error occurred: {e}")

API Reference

GDriveClient The main class for interacting with Google Drive.

  • download_file(directory_path, file_id, file_name, mime_type=None): Downloads a file. Use mime_type to export Google Workspace files (e.g., application/pdf).

  • upload_file(file_path, folder_id, **metadata): Uploads a local file to a specified folder.

  • retrieve_file_content(file_id): Retrieves file content as a BytesIO object for in-memory use.

  • list_files(query, **list_params): Lists files using the standard Google Drive API query syntax.

  • find_folder_id_by_path(start_folder_id, path_segments): Navigates a path to find a folder's ID.

  • retrieve_sheet_data(spreadsheet_id, sheet_range): Retrieves data |from a Google Sheet.

GDriveClientConfig Handles configuration and authentication.

  • **init**(config_dir_path, scope): Initializes the configuration manager.

  • get_credentials() : Returns valid OAuth2 credentials, handling the auth flow and token refreshing.

Contributing

Contributions are welcome! If you have a feature request, bug report, or pull request, please open an issue or PR on the GitHub repository.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gdrive_suite-0.1.1.tar.gz (14.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gdrive_suite-0.1.1-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file gdrive_suite-0.1.1.tar.gz.

File metadata

  • Download URL: gdrive_suite-0.1.1.tar.gz
  • Upload date:
  • Size: 14.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for gdrive_suite-0.1.1.tar.gz
Algorithm Hash digest
SHA256 1f6097006c516800b9a4f60cdf27ba694da87713be43c5edf9a384448c426003
MD5 e83e2b5acf307b79883f5a8d1c4c2592
BLAKE2b-256 67704c9049402d9a93ed607860861ee389274b2d36ef677db29956bc16eb9641

See more details on using hashes here.

Provenance

The following attestation bundles were made for gdrive_suite-0.1.1.tar.gz:

Publisher: publish.yml on TheLionCoder/gdrive-suite

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file gdrive_suite-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: gdrive_suite-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 12.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for gdrive_suite-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4690f2351ce7e5794a8d4a13eb81478a98fd510992ddc4757648c3412fbb2816
MD5 850cb76455da6fad093826d1519657fe
BLAKE2b-256 cf4ee07819d5dd05991c50a840180b03f76c1c6c95a5e5f8072ffdc4e96ec033

See more details on using hashes here.

Provenance

The following attestation bundles were made for gdrive_suite-0.1.1-py3-none-any.whl:

Publisher: publish.yml on TheLionCoder/gdrive-suite

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page