Microsoft Azure Data Tables Client Library for Python
90
Table-specific operations for entity management including CRUD operations, batch transactions, querying with filtering and pagination, and access policy management.
Create and configure TableClient for table-specific operations with various authentication methods and initialization patterns.
class TableClient:
def __init__(
self,
endpoint: str,
table_name: str,
*,
credential=None,
audience: str = None,
api_version: str = None,
**kwargs
):
"""
Initialize TableClient for table operations.
Parameters:
- endpoint: Full URL to the Tables account
- table_name: Name of the table
- credential: Authentication credential
- audience: Service audience for token authentication
- api_version: Storage API version to use
"""
@classmethod
def from_connection_string(
cls,
conn_str: str,
table_name: str,
**kwargs
) -> "TableClient":
"""
Create client from connection string.
Parameters:
- conn_str: Connection string with account credentials
- table_name: Name of the table
Returns:
TableClient instance
"""
@classmethod
def from_table_url(
cls,
table_url: str,
*,
credential=None,
**kwargs
) -> "TableClient":
"""
Create client from table URL.
Parameters:
- table_url: Complete URL to the table
- credential: Authentication credential
Returns:
TableClient instance
"""from azure.data.tables import TableClient
from azure.core.credentials import AzureNamedKeyCredential
# From connection string
table_client = TableClient.from_connection_string(
conn_str="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey",
table_name="customers"
)
# From endpoint and credential
credential = AzureNamedKeyCredential("myaccount", "mykey")
table_client = TableClient(
endpoint="https://myaccount.table.core.windows.net/",
table_name="customers",
credential=credential
)
# From table URL
table_client = TableClient.from_table_url(
table_url="https://myaccount.table.core.windows.net/customers",
credential=credential
)Create and delete tables directly through the table client.
class TableClient:
def create_table(self, **kwargs) -> TableItem:
"""
Create the table.
Returns:
TableItem representing the created table
Raises:
ResourceExistsError: If table already exists
"""
def delete_table(self, **kwargs) -> None:
"""
Delete the table.
Raises:
ResourceNotFoundError: If table doesn't exist
"""Complete Create, Read, Update, Delete operations for table entities with flexible entity representations.
class TableClient:
def create_entity(
self,
entity: Union[TableEntity, Mapping[str, Any]],
**kwargs
) -> Dict[str, Any]:
"""
Insert a new entity into the table.
Parameters:
- entity: Entity data (TableEntity or dictionary)
Returns:
Dictionary with entity metadata including etag
Raises:
ResourceExistsError: If entity already exists
"""
def get_entity(
self,
partition_key: str,
row_key: str,
*,
select: List[str] = None,
**kwargs
) -> TableEntity:
"""
Retrieve a single entity by partition and row key.
Parameters:
- partition_key: Entity partition key
- row_key: Entity row key
- select: List of property names to return
Returns:
TableEntity with the requested entity data
Raises:
ResourceNotFoundError: If entity doesn't exist
"""
def update_entity(
self,
entity: Union[TableEntity, Mapping[str, Any]],
mode: UpdateMode = UpdateMode.MERGE,
**kwargs
) -> Dict[str, Any]:
"""
Update an existing entity.
Parameters:
- entity: Entity data with PartitionKey and RowKey
- mode: Update mode (MERGE or REPLACE)
Returns:
Dictionary with updated entity metadata
Raises:
ResourceNotFoundError: If entity doesn't exist
"""
def upsert_entity(
self,
entity: Union[TableEntity, Mapping[str, Any]],
mode: UpdateMode = UpdateMode.MERGE,
**kwargs
) -> Dict[str, Any]:
"""
Insert or update entity (upsert operation).
Parameters:
- entity: Entity data with PartitionKey and RowKey
- mode: Update mode for existing entities
Returns:
Dictionary with entity metadata
"""
def delete_entity(
self,
partition_key: str,
row_key: str,
*,
etag: Optional[str] = None,
match_condition: Optional[MatchConditions] = None,
**kwargs
) -> None:
"""
Delete an entity from the table using partition and row keys.
Parameters:
- partition_key: The partition key of the entity
- row_key: The row key of the entity
- etag: Optional etag for optimistic concurrency
- match_condition: Optional condition for conditional delete
Raises:
ResourceNotFoundError: If entity doesn't exist
"""
def delete_entity(
self,
entity: Union[TableEntity, Mapping[str, Any]],
*,
etag: Optional[str] = None,
match_condition: Optional[MatchConditions] = None,
**kwargs
) -> None:
"""
Delete an entity from the table using entity object.
Parameters:
- entity: Entity with PartitionKey and RowKey properties
- etag: Optional etag for optimistic concurrency (overrides entity etag)
- match_condition: Optional condition for conditional delete
Raises:
ResourceNotFoundError: If entity doesn't exist
"""from azure.data.tables import TableClient, TableEntity, UpdateMode
table_client = TableClient.from_connection_string(conn_str, "customers")
# Create entity
entity = TableEntity()
entity["PartitionKey"] = "customer"
entity["RowKey"] = "001"
entity["Name"] = "John Doe"
entity["Email"] = "john@example.com"
entity["Age"] = 30
result = table_client.create_entity(entity)
print(f"Created entity with etag: {result['etag']}")
# Get entity
retrieved = table_client.get_entity("customer", "001")
print(f"Name: {retrieved['Name']}")
# Update entity (merge)
retrieved["Age"] = 31
table_client.update_entity(retrieved, mode=UpdateMode.MERGE)
# Upsert entity
new_entity = {
"PartitionKey": "customer",
"RowKey": "002",
"Name": "Jane Smith",
"Email": "jane@example.com"
}
table_client.upsert_entity(new_entity)
# Delete entity by keys
table_client.delete_entity("customer", "001")
# Delete entity by object
table_client.delete_entity(retrieved)Advanced querying capabilities with OData filters, pagination, and property selection.
class TableClient:
def list_entities(
self,
*,
results_per_page: int = None,
select: List[str] = None,
**kwargs
) -> ItemPaged[TableEntity]:
"""
List all entities in the table.
Parameters:
- results_per_page: Maximum entities per page
- select: List of property names to return
Returns:
Paged iterator of TableEntity objects
"""
def query_entities(
self,
query_filter: str,
*,
results_per_page: int = None,
parameters: Dict[str, Any] = None,
select: List[str] = None,
**kwargs
) -> ItemPaged[TableEntity]:
"""
Query entities with OData filter expression.
Parameters:
- query_filter: OData filter expression
- results_per_page: Maximum results per page
- parameters: Parameter substitution values
- select: List of property names to return
Returns:
Paged iterator of matching TableEntity objects
"""from azure.data.tables import TableClient
table_client = TableClient.from_connection_string(conn_str, "customers")
# List all entities
for entity in table_client.list_entities():
print(f"Customer: {entity['Name']}")
# Query with filter
entities = table_client.query_entities(
query_filter="Age gt 25 and PartitionKey eq 'customer'",
select=["Name", "Email", "Age"]
)
for entity in entities:
print(f"Name: {entity['Name']}, Age: {entity['Age']}")
# Query with parameters
entities = table_client.query_entities(
query_filter="Age gt @age_limit",
parameters={"age_limit": 30}
)
# Paginated results
pages = table_client.query_entities(
query_filter="PartitionKey eq 'customer'",
results_per_page=10
)
for page in pages.by_page():
print(f"Page with {len(list(page))} entities")Execute multiple operations in a single atomic transaction for improved performance and consistency.
class TableClient:
def submit_transaction(
self,
operations: Iterable[Union[
Tuple[str, Union[TableEntity, Mapping[str, Any]]],
Tuple[str, Union[TableEntity, Mapping[str, Any]], Mapping[str, Any]]
]],
**kwargs
) -> List[Mapping[str, Any]]:
"""
Submit a batch of operations as a single transaction.
Parameters:
- operations: List of (operation_type, entity) or (operation_type, entity, options) tuples
Operation types:
- "create": Insert new entity
- "update": Update existing entity
- "upsert": Insert or update entity
- "delete": Delete entity
Returns:
List of operation results
Raises:
TableTransactionError: If any operation fails
Note:
All entities in a batch must have the same PartitionKey
Maximum 100 operations per batch
"""from azure.data.tables import TableClient, UpdateMode
table_client = TableClient.from_connection_string(conn_str, "customers")
# Prepare batch operations
operations = [
("create", {
"PartitionKey": "batch",
"RowKey": "001",
"Name": "Customer 1"
}),
("create", {
"PartitionKey": "batch",
"RowKey": "002",
"Name": "Customer 2"
}),
("update", {
"PartitionKey": "batch",
"RowKey": "003",
"Name": "Updated Customer 3"
}, {"mode": UpdateMode.REPLACE}),
("delete", {
"PartitionKey": "batch",
"RowKey": "004"
})
]
# Submit transaction
try:
results = table_client.submit_transaction(operations)
print(f"Successfully processed {len(results)} operations")
except TableTransactionError as e:
print(f"Transaction failed at operation {e.index}: {e.message}")Manage stored access policies for table-level permissions and SAS token generation.
class TableClient:
def get_table_access_policy(
self,
**kwargs
) -> Dict[str, Optional[TableAccessPolicy]]:
"""
Get stored access policies for the table.
Returns:
Dictionary mapping policy IDs to TableAccessPolicy objects
"""
def set_table_access_policy(
self,
signed_identifiers: Mapping[str, Optional[TableAccessPolicy]],
**kwargs
) -> None:
"""
Set stored access policies for the table.
Parameters:
- signed_identifiers: Dictionary mapping policy IDs to policies
Use None value to delete a policy
"""from azure.data.tables import TableClient, TableAccessPolicy
from datetime import datetime, timedelta
table_client = TableClient.from_connection_string(conn_str, "customers")
# Create access policy
policy = TableAccessPolicy(
start=datetime.utcnow(),
expiry=datetime.utcnow() + timedelta(hours=1),
permission="r" # read-only
)
# Set access policies
table_client.set_table_access_policy({
"read-policy": policy,
"old-policy": None # Delete this policy
})
# Get current policies
policies = table_client.get_table_access_policy()
for policy_id, policy in policies.items():
if policy:
print(f"Policy {policy_id}: {policy.permission}")class TableClient:
@property
def account_name(self) -> str:
"""The name of the Tables account."""
@property
def table_name(self) -> str:
"""The name of the table."""
@property
def scheme(self) -> str:
"""The scheme component in the full URL."""
@property
def url(self) -> str:
"""The full endpoint URL to this table."""
@property
def api_version(self) -> str:
"""The version of the Storage API used for requests."""
@property
def credential(self):
"""The credentials with which to authenticate."""class UpdateMode(Enum):
"""Entity update modes."""
REPLACE = "replace" # Replace entire entity
MERGE = "merge" # Merge properties with existing entity
class TableAccessPolicy:
"""Access policy for shared access signatures."""
def __init__(
self,
start: Union[datetime, str] = None,
expiry: Union[datetime, str] = None,
permission: str = None
): ...Install with Tessl CLI
npx tessl i tessl/pypi-azure-data-tablesdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10