Azure Cosmos DB Table Client Library (Legacy)

1.0.6 · deprecated · verified Fri Apr 10

This is an older client library for interacting with Azure Cosmos DB Table API and Azure Table Storage. It provides functionalities for creating, managing, and querying tables and entities. As of version 1.0.6, it is considered a legacy library, with the actively maintained `azure-data-tables` package being the recommended replacement. The library is no longer actively developed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `TableService` client, create a table, insert an entity, and retrieve an entity using connection string or account credentials. Remember to set `AZURE_STORAGE_CONNECTION_STRING` or `AZURE_STORAGE_ACCOUNT_NAME` and `AZURE_STORAGE_ACCOUNT_KEY` environment variables.

import os
from azure.cosmosdb.table import TableService, Entity

# Set these environment variables or replace with actual values
# AZURE_STORAGE_CONNECTION_STRING (preferred) or AZURE_STORAGE_ACCOUNT_NAME and AZURE_STORAGE_ACCOUNT_KEY
connection_string = os.environ.get("AZURE_STORAGE_CONNECTION_STRING", "DefaultEndpointsProtocol=https;AccountName=your_account_name;AccountKey=your_account_key;EndpointSuffix=core.windows.net")
account_name = os.environ.get("AZURE_STORAGE_ACCOUNT_NAME", "your_account_name")
account_key = os.environ.get("AZURE_STORAGE_ACCOUNT_KEY", "your_account_key")

# Initialize the TableService client
# If connection string is not valid, try with account name/key
if "DefaultEndpointsProtocol" in connection_string and "your_account_name" not in connection_string:
    table_service = TableService(connection_string=connection_string)
else:
    table_service = TableService(account_name=account_name, account_key=account_key)

table_name = "mytesttable"

try:
    # Create table if it doesn't exist
    print(f"Creating table '{table_name}' if it doesn't exist...")
    table_service.create_table(table_name)
    print(f"Table '{table_name}' created or already exists.")

    # Insert an entity
    task = {'PartitionKey': 'tasks', 'RowKey': '1', 'description': 'Learn Python SDK', 'priority': 100}
    print(f"Inserting entity: {task}")
    table_service.insert_entity(table_name, task)
    print("Entity inserted.")

    # Retrieve an entity
    print(f"Retrieving entity with PartitionKey='tasks', RowKey='1'")
    retrieved_task = table_service.get_entity(table_name, 'tasks', '1')
    print(f"Retrieved entity: {retrieved_task['description']}, Priority: {retrieved_task['priority']}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your Azure Storage/Cosmos DB connection details are correct and the account has table API enabled.")

# Optional: Clean up the table
# try:
#     print(f"Deleting table '{table_name}'...")
#     table_service.delete_table(table_name)
#     print(f"Table '{table_name}' deleted.")
# except Exception as e:
#     print(f"Error deleting table: {e}")

view raw JSON →