pytd - Treasure Data Driver

2.4.0 · active · verified Wed Apr 15

pytd is the official Treasure Data Driver for Python, providing a client for interacting with Treasure Data's services. It allows users to query data, load data into tables, and manage databases. The current version is 2.4.0, and it maintains a regular release cadence, typically with several updates per year.

Warnings

Install

Imports

Quickstart

This quickstart initializes a `pytd` client using environment variables for the API key and server. It then demonstrates how to list available databases. For actual data querying or loading, ensure your Treasure Data API key is valid and you have existing databases/tables that the client can access.

import os
from pytd.client import Client

# Set your Treasure Data API key and server in environment variables
# e.g., export TD_API_KEY="YOUR_API_KEY"
# e.g., export TD_API_SERVER="https://api.treasuredata.com"

api_key = os.environ.get('TD_API_KEY', '')
api_server = os.environ.get('TD_API_SERVER', 'https://api.treasuredata.com')

if not api_key:
    print("Warning: TD_API_KEY environment variable not set. Client may fail to authenticate.")

try:
    # Initialize the client
    client = Client(apikey=api_key, endpoint=api_server)

    # List databases
    databases = client.list_databases()
    print(f"Databases: {[db.name for db in databases]}")

    # Example: Execute a simple query (replace 'sample_datasets' and 'www_access' with your actual db/table)
    # This part requires a valid database and table to exist in your Treasure Data account.
    if databases and len(databases) > 0:
        first_db_name = databases[0].name
        print(f"Using first database found: {first_db_name}")
        # Example query (uncomment and modify with an actual table in your account):
        # query_result = client.query(f'SELECT count(*) FROM {first_db_name}.your_table_name_here')
        # print(f"Query result count: {query_result.fetchall()[0][0]}")
    else:
        print("No databases found or API key/server invalid.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your TD_API_KEY and TD_API_SERVER are correctly set and accessible, and you have network connectivity.")

view raw JSON →