CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-data-tables

Microsoft Azure Data Tables Client Library for Python

90

0.96x
Overview
Eval results
Files

entity-data-types.mddocs/

Entity Data Types

Data modeling capabilities for Azure Tables including entity representation, type-safe properties, metadata handling, and Entity Data Model (EDM) type specifications for precise data representation.

Capabilities

Table Entity

Dictionary-based entity representation with metadata support for Azure Tables operations.

class TableEntity(dict):
    """
    Table entity that extends dict with metadata support.
    
    Inherits all dictionary methods and adds metadata handling.
    PartitionKey and RowKey are required for all operations.
    """
    
    metadata: EntityMetadata
    
    def __init__(self, *args, **kwargs):
        """
        Initialize TableEntity.
        
        Can be initialized like a standard dictionary:
        - TableEntity() - empty entity
        - TableEntity({"key": "value"}) - from dict
        - TableEntity(key="value") - from kwargs
        """

Usage Example

from azure.data.tables import TableEntity

# Create empty entity
entity = TableEntity()
entity["PartitionKey"] = "customer"
entity["RowKey"] = "001"
entity["Name"] = "John Doe"
entity["Age"] = 30

# Create from dictionary
entity_data = {
    "PartitionKey": "product",
    "RowKey": "item001",
    "Name": "Widget",
    "Price": 29.99,
    "InStock": True
}
entity = TableEntity(entity_data)

# Create with kwargs
entity = TableEntity(
    PartitionKey="order",
    RowKey="12345",
    CustomerName="Jane Smith",
    Total=149.99
)

# Access like dictionary
print(entity["Name"])
entity["Status"] = "Active"

# Access metadata after operations
print(f"ETag: {entity.metadata.get('etag')}")
print(f"Timestamp: {entity.metadata.get('timestamp')}")

Entity Property

Explicitly typed entity property for precise data type control and EDM type specification.

class EntityProperty(NamedTuple):
    """
    Explicitly typed entity property.
    
    Used when you need to specify exact EDM types for properties
    instead of relying on automatic type inference.
    """
    
    value: Any
    edm_type: Union[str, EdmType]

Usage Example

from azure.data.tables import TableEntity, EntityProperty, EdmType
from datetime import datetime
import uuid

# Create entity with explicit types
entity = TableEntity()
entity["PartitionKey"] = "typed"
entity["RowKey"] = "001"

# Explicit string type
entity["Description"] = EntityProperty("Product description", EdmType.STRING)

# Explicit datetime type
entity["Created"] = EntityProperty(datetime.utcnow(), EdmType.DATETIME)

# Explicit GUID type
entity["ProductId"] = EntityProperty(str(uuid.uuid4()), EdmType.GUID)

# Explicit binary data
entity["Thumbnail"] = EntityProperty(b"image_data", EdmType.BINARY)

# Large integer (beyond JavaScript int53 range)
entity["BigNumber"] = EntityProperty(9007199254740992, EdmType.INT64)

# Insert entity with explicit types
table_client.create_entity(entity)

EDM Type System

Entity Data Model types for precise data representation in Azure Tables.

class EdmType(Enum):
    """
    Entity Data Model types for Table service.
    
    These types ensure proper serialization and deserialization
    of data between client and service.
    """
    
    STRING = "Edm.String"        # String data (default for str)
    INT32 = "Edm.Int32"          # 32-bit integer (default for int)
    INT64 = "Edm.Int64"          # 64-bit large integer
    BOOLEAN = "Edm.Boolean"      # Boolean value (default for bool)
    DATETIME = "Edm.DateTime"    # Date and time (default for datetime)
    GUID = "Edm.Guid"           # GUID/UUID identifier
    BINARY = "Edm.Binary"       # Binary data (default for bytes)
    DOUBLE = "Edm.Double"       # Double precision float (default for float)

Usage Example

from azure.data.tables import TableEntity, EntityProperty, EdmType
from datetime import datetime
import uuid

entity = TableEntity()
entity["PartitionKey"] = "types"
entity["RowKey"] = "demo"

# String type (explicit)
entity["Name"] = EntityProperty("Product Name", EdmType.STRING)

# Integer types
entity["Quantity"] = EntityProperty(100, EdmType.INT32)
entity["SerialNumber"] = EntityProperty(1234567890123456789, EdmType.INT64)

# Boolean type
entity["IsActive"] = EntityProperty(True, EdmType.BOOLEAN)

# DateTime type
entity["CreatedAt"] = EntityProperty(datetime.utcnow(), EdmType.DATETIME)

# GUID type
entity["UniqueId"] = EntityProperty(str(uuid.uuid4()), EdmType.GUID)

# Binary type
entity["Data"] = EntityProperty(b"binary_content", EdmType.BINARY)

# Double precision float
entity["Price"] = EntityProperty(123.456789, EdmType.DOUBLE)

# When you retrieve the entity, types are preserved
retrieved = table_client.get_entity("types", "demo")
print(f"Price type: {type(retrieved['Price'])}")  # float

Entity Metadata

Metadata structure containing system-generated and service-managed entity information.

class EntityMetadata(TypedDict):
    """
    Metadata associated with table entities.
    
    Automatically populated by Azure Tables service during operations.
    Used for optimistic concurrency control and entity tracking.
    """
    
    etag: Required[Optional[str]]              # Entity tag for concurrency
    timestamp: Required[Optional[datetime]]    # Last modified timestamp
    id: str                                   # Entity ID (optional)
    type: str                                # Type name (optional)
    editLink: str                            # Edit link (optional)

Usage Example

from azure.data.tables import TableClient, TableEntity

table_client = TableClient.from_connection_string(conn_str, "products")

# Create entity
entity = TableEntity(
    PartitionKey="electronics",
    RowKey="laptop001",
    Name="Gaming Laptop",
    Price=1299.99
)

# Insert entity
result = table_client.create_entity(entity)
print(f"Created with ETag: {result['etag']}")

# Retrieve entity with metadata
retrieved = table_client.get_entity("electronics", "laptop001")

# Access metadata
print(f"ETag: {retrieved.metadata['etag']}")
print(f"Last Modified: {retrieved.metadata['timestamp']}")

# Use ETag for optimistic concurrency
retrieved['Price'] = 1199.99
try:
    table_client.update_entity(
        retrieved,
        etag=retrieved.metadata['etag'],
        match_condition=MatchConditions.IfNotModified
    )
    print("Update successful")
except ResourceModifiedError:
    print("Entity was modified by another process")

Type Inference and Conversion

Automatic type inference rules and conversion behaviors for entity properties.

# Automatic type mapping for common Python types:
# 
# Python type     -> EDM type
# str            -> Edm.String
# int            -> Edm.Int32 (if within range) or Edm.Int64
# float          -> Edm.Double  
# bool           -> Edm.Boolean
# datetime       -> Edm.DateTime
# bytes          -> Edm.Binary
# uuid.UUID      -> Edm.Guid (as string)

# Special values:
# None           -> null property (omitted in some operations)
# Large integers -> Automatically promoted to Edm.Int64

Usage Example

from azure.data.tables import TableEntity
from datetime import datetime
import uuid

# Automatic type inference
entity = TableEntity()
entity["PartitionKey"] = "auto"
entity["RowKey"] = "001"

# These will be automatically typed:
entity["Name"] = "Product"                    # -> Edm.String
entity["Count"] = 42                         # -> Edm.Int32
entity["BigCount"] = 9007199254740992        # -> Edm.Int64
entity["Price"] = 99.99                      # -> Edm.Double
entity["Active"] = True                      # -> Edm.Boolean
entity["Created"] = datetime.utcnow()        # -> Edm.DateTime
entity["Data"] = b"bytes"                    # -> Edm.Binary
entity["Id"] = str(uuid.uuid4())             # -> Edm.String (not GUID)

# For GUID type, use explicit EntityProperty
entity["GuidId"] = EntityProperty(str(uuid.uuid4()), EdmType.GUID)

table_client.create_entity(entity)

Advanced Entity Patterns

Common patterns for working with complex entity structures and data modeling.

Usage Example

from azure.data.tables import TableEntity, EntityProperty, EdmType
from datetime import datetime
import json

# Complex entity with mixed types
order = TableEntity()
order["PartitionKey"] = f"order_{datetime.now().year}"
order["RowKey"] = "12345"

# Standard properties
order["CustomerName"] = "John Doe"
order["OrderDate"] = datetime.utcnow()
order["Total"] = 299.99
order["Status"] = "pending"

# JSON data as string
order_items = [
    {"product": "Widget", "quantity": 2, "price": 99.99},
    {"product": "Gadget", "quantity": 1, "price": 99.99}
]
order["Items"] = json.dumps(order_items)

# Large tracking number
order["TrackingNumber"] = EntityProperty(1234567890123456789, EdmType.INT64)

# Binary attachment
order["Invoice"] = EntityProperty(b"PDF_content", EdmType.BINARY)

table_client.create_entity(order)

# Retrieve and process
retrieved = table_client.get_entity(order["PartitionKey"], order["RowKey"])
items = json.loads(retrieved["Items"])
print(f"Order has {len(items)} items")

Common Type Aliases

# Type aliases used throughout the library
EntityType = Union[TableEntity, Mapping[str, Any]]
"""Entity can be TableEntity or any mapping (dict-like) object"""

OperationType = Union[TransactionOperation, str]
"""Operation type for batch transactions"""

TransactionOperationType = Union[
    Tuple[OperationType, EntityType],
    Tuple[OperationType, EntityType, Mapping[str, Any]]
]
"""Complete transaction operation specification with optional parameters"""

Install with Tessl CLI

npx tessl i tessl/pypi-azure-data-tables

docs

async-operations.md

batch-operations.md

entity-data-types.md

error-handling.md

index.md

security-access-control.md

service-management.md

table-operations.md

tile.json