|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +# ------------------------------------------------------------------------- |
| 4 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 | +# Licensed under the MIT License. See License.txt in the project root for |
| 6 | +# license information. |
| 7 | +# -------------------------------------------------------------------------- |
| 8 | + |
| 9 | +""" |
| 10 | +FILE: sample_custom_encoder_dataclass_async.py |
| 11 | +
|
| 12 | +DESCRIPTION: |
| 13 | + These samples demonstrate the following: inserting entities into a table |
| 14 | + and deleting entities from a table. |
| 15 | +
|
| 16 | +USAGE: |
| 17 | + python sample_custom_encoder_dataclass_async.py |
| 18 | +
|
| 19 | + Set the environment variables with your own values before running the sample: |
| 20 | + 1) TABLES_STORAGE_ENDPOINT_SUFFIX - the Table service account URL suffix |
| 21 | + 2) TABLES_STORAGE_ACCOUNT_NAME - the name of the storage account |
| 22 | + 3) TABLES_PRIMARY_STORAGE_ACCOUNT_KEY - the storage account access key |
| 23 | +""" |
| 24 | +import os |
| 25 | +import asyncio |
| 26 | +from datetime import datetime, timezone |
| 27 | +from uuid import uuid4, UUID |
| 28 | +from dotenv import find_dotenv, load_dotenv |
| 29 | +from dataclasses import dataclass, asdict |
| 30 | +from typing import Dict, Union, Optional |
| 31 | +from azure.data.tables import TableEntityEncoderABC, UpdateMode |
| 32 | +from azure.data.tables.aio import TableClient |
| 33 | + |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class Car: |
| 37 | + partition_key: str |
| 38 | + row_key: UUID |
| 39 | + price: Optional[float] = None |
| 40 | + last_updated: Optional[datetime] = None |
| 41 | + product_id: Optional[UUID] = None |
| 42 | + inventory_count: Optional[int] = None |
| 43 | + barcode: Optional[bytes] = None |
| 44 | + color: Optional[str] = None |
| 45 | + maker: Optional[str] = None |
| 46 | + model: Optional[str] = None |
| 47 | + production_date: Optional[datetime] = None |
| 48 | + mileage: Optional[int] = None |
| 49 | + is_second_hand: Optional[bool] = None |
| 50 | + |
| 51 | + |
| 52 | +class MyEncoder(TableEntityEncoderABC[Car]): |
| 53 | + def prepare_key(self, key: UUID) -> str: # type: ignore[override] |
| 54 | + return super().prepare_key(str(key)) |
| 55 | + |
| 56 | + def encode_entity(self, entity: Car) -> Dict[str, Union[str, int, float, bool]]: |
| 57 | + encoded = {} |
| 58 | + for key, value in asdict(entity).items(): |
| 59 | + if key == "partition_key": |
| 60 | + encoded["PartitionKey"] = value # this property should be "PartitionKey" in encoded result |
| 61 | + continue |
| 62 | + if key == "row_key": |
| 63 | + encoded["RowKey"] = str(value) # this property should be "RowKey" in encoded result |
| 64 | + continue |
| 65 | + edm_type, value = self.prepare_value(key, value) |
| 66 | + if edm_type: |
| 67 | + encoded[f"{key}@odata.type"] = edm_type.value if hasattr(edm_type, "value") else edm_type |
| 68 | + encoded[key] = value |
| 69 | + return encoded |
| 70 | + |
| 71 | + |
| 72 | +class InsertUpdateDeleteEntity(object): |
| 73 | + def __init__(self): |
| 74 | + load_dotenv(find_dotenv()) |
| 75 | + self.access_key = os.environ["TABLES_PRIMARY_STORAGE_ACCOUNT_KEY"] |
| 76 | + self.endpoint_suffix = os.environ["TABLES_STORAGE_ENDPOINT_SUFFIX"] |
| 77 | + self.account_name = os.environ["TABLES_STORAGE_ACCOUNT_NAME"] |
| 78 | + self.endpoint = f"{self.account_name}.table.{self.endpoint_suffix}" |
| 79 | + self.connection_string = f"DefaultEndpointsProtocol=https;AccountName={self.account_name};AccountKey={self.access_key};EndpointSuffix={self.endpoint_suffix}" |
| 80 | + self.table_name = "CustomEncoderDataClassAsync" |
| 81 | + |
| 82 | + self.entity = Car( |
| 83 | + partition_key="PK", |
| 84 | + row_key=uuid4(), |
| 85 | + price=4.99, |
| 86 | + last_updated=datetime.today(), |
| 87 | + product_id=uuid4(), |
| 88 | + inventory_count=42, |
| 89 | + barcode=b"135aefg8oj0ld58", # cspell:disable-line |
| 90 | + color="white", |
| 91 | + maker="maker", |
| 92 | + model="model", |
| 93 | + production_date=datetime(year=2014, month=4, day=1, hour=9, minute=30, second=45, tzinfo=timezone.utc), |
| 94 | + mileage=2**31, # an int64 integer |
| 95 | + is_second_hand=True, |
| 96 | + ) |
| 97 | + |
| 98 | + async def create_delete_entity(self): |
| 99 | + table_client = TableClient.from_connection_string(self.connection_string, self.table_name) |
| 100 | + async with table_client: |
| 101 | + await table_client.create_table() |
| 102 | + |
| 103 | + result = await table_client.create_entity(entity=self.entity, encoder=MyEncoder()) |
| 104 | + print(f"Created entity: {result}") |
| 105 | + |
| 106 | + result = await table_client.get_entity( |
| 107 | + self.entity.partition_key, |
| 108 | + self.entity.row_key, # type: ignore[arg-type] # intend to pass a non-string RowKey |
| 109 | + encoder=MyEncoder(), |
| 110 | + ) |
| 111 | + print(f"Get entity result: {result}") |
| 112 | + |
| 113 | + await table_client.delete_entity( |
| 114 | + partition_key=self.entity.partition_key, |
| 115 | + row_key=self.entity.row_key, # type: ignore[call-overload] # intend to pass a non-string RowKey |
| 116 | + encoder=MyEncoder(), |
| 117 | + ) |
| 118 | + print("Successfully deleted!") |
| 119 | + |
| 120 | + await table_client.delete_table() |
| 121 | + print("Cleaned up") |
| 122 | + |
| 123 | + async def upsert_update_entities(self): |
| 124 | + table_client = TableClient.from_connection_string( |
| 125 | + self.connection_string, table_name=f"{self.table_name}UpsertUpdate" |
| 126 | + ) |
| 127 | + |
| 128 | + async with table_client: |
| 129 | + await table_client.create_table() |
| 130 | + |
| 131 | + entity1 = Car( |
| 132 | + partition_key="PK", |
| 133 | + row_key=uuid4(), |
| 134 | + price=4.99, |
| 135 | + last_updated=datetime.today(), |
| 136 | + product_id=uuid4(), |
| 137 | + inventory_count=42, |
| 138 | + barcode=b"135aefg8oj0ld58", # cspell:disable-line |
| 139 | + ) |
| 140 | + entity2 = Car( |
| 141 | + partition_key=entity1.partition_key, |
| 142 | + row_key=entity1.row_key, |
| 143 | + color="red", |
| 144 | + maker="maker2", |
| 145 | + model="model2", |
| 146 | + production_date=datetime(year=2014, month=4, day=1, hour=9, minute=30, second=45, tzinfo=timezone.utc), |
| 147 | + mileage=2**31, # an int64 integer |
| 148 | + is_second_hand=True, |
| 149 | + ) |
| 150 | + |
| 151 | + await table_client.upsert_entity(mode=UpdateMode.REPLACE, entity=entity2, encoder=MyEncoder()) |
| 152 | + inserted_entity = await table_client.get_entity( |
| 153 | + entity2.partition_key, |
| 154 | + entity2.row_key, # type: ignore[arg-type] # intend to pass a non-string RowKey |
| 155 | + encoder=MyEncoder(), |
| 156 | + ) |
| 157 | + print(f"Inserted entity: {inserted_entity}") |
| 158 | + |
| 159 | + await table_client.upsert_entity(mode=UpdateMode.MERGE, entity=entity1, encoder=MyEncoder()) |
| 160 | + merged_entity = await table_client.get_entity( |
| 161 | + entity1.partition_key, |
| 162 | + entity1.row_key, # type: ignore[arg-type] # intend to pass a non-string RowKey |
| 163 | + encoder=MyEncoder(), |
| 164 | + ) |
| 165 | + print(f"Merged entity: {merged_entity}") |
| 166 | + |
| 167 | + entity3 = Car( |
| 168 | + partition_key=entity1.partition_key, |
| 169 | + row_key=entity2.row_key, |
| 170 | + color="white", |
| 171 | + ) |
| 172 | + await table_client.update_entity(mode=UpdateMode.REPLACE, entity=entity3, encoder=MyEncoder()) |
| 173 | + replaced_entity = await table_client.get_entity( |
| 174 | + entity3.partition_key, |
| 175 | + entity3.row_key, # type: ignore[arg-type] # intend to pass a non-string RowKey |
| 176 | + encoder=MyEncoder(), |
| 177 | + ) |
| 178 | + print(f"Replaced entity: {replaced_entity}") |
| 179 | + |
| 180 | + await table_client.update_entity(mode=UpdateMode.REPLACE, entity=entity2, encoder=MyEncoder()) |
| 181 | + merged_entity = await table_client.get_entity( |
| 182 | + entity2.partition_key, |
| 183 | + entity2.row_key, # type: ignore[arg-type] # intend to pass a non-string RowKey |
| 184 | + encoder=MyEncoder(), |
| 185 | + ) |
| 186 | + print(f"Merged entity: {merged_entity}") |
| 187 | + |
| 188 | + await table_client.delete_table() |
| 189 | + print("Cleaned up") |
| 190 | + |
| 191 | + |
| 192 | +async def main(): |
| 193 | + ide = InsertUpdateDeleteEntity() |
| 194 | + await ide.create_delete_entity() |
| 195 | + await ide.upsert_update_entities() |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + asyncio.run(main()) |
0 commit comments