File: sample_batching_async.py

package info (click to toggle)
python-azure 20230112%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 749,544 kB
  • sloc: python: 6,815,827; javascript: 287; makefile: 195; xml: 109; sh: 105
file content (104 lines) | stat: -rw-r--r-- 3,788 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# coding: utf-8

# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

"""
FILE: sample_batching_async.py

DESCRIPTION:
    These samples demonstrate how to use the batch transaction API to perform multiple
    operations within a single request

USAGE:
    python sample_batching_async.py

    Set the environment variables with your own values before running the sample:
    1) TABLES_STORAGE_ENDPOINT_SUFFIX - the Table service account URL suffix
    2) TABLES_STORAGE_ACCOUNT_NAME - the name of the storage account
    3) TABLES_PRIMARY_STORAGE_ACCOUNT_KEY - the storage account access key
"""


import os
import asyncio
from dotenv import find_dotenv, load_dotenv


class CreateClients(object):
    def __init__(self):
        load_dotenv(find_dotenv())
        self.access_key = os.getenv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
        self.endpoint_suffix = os.getenv("TABLES_STORAGE_ENDPOINT_SUFFIX")
        self.account_name = os.getenv("TABLES_STORAGE_ACCOUNT_NAME")
        self.connection_string = "DefaultEndpointsProtocol=https;AccountName={};AccountKey={};EndpointSuffix={}".format(
            self.account_name, self.access_key, self.endpoint_suffix
        )
        self.table_name = "sampleTransactionAsync"

    async def _create_entities(self):
        from azure.core.exceptions import ResourceExistsError

        self.entity1 = {"PartitionKey": "pk001", "RowKey": "rk001", "Value": 4, "day": "Monday", "float": 4.003}
        self.entity2 = {"PartitionKey": "pk001", "RowKey": "rk002", "Value": 4, "day": "Tuesday", "float": 4.003}
        self.entity3 = {"PartitionKey": "pk001", "RowKey": "rk003", "Value": 4, "day": "Wednesday", "float": 4.003}
        self.entity4 = {"PartitionKey": "pk001", "RowKey": "rk004", "Value": 4, "day": "Thursday", "float": 4.003}

        entities = [self.entity2, self.entity3, self.entity4]

        for entity in entities:
            try:
                await self.table_client.create_entity(entity)
            except ResourceExistsError:
                print("entity already exists")
                pass

    async def sample_transaction(self):
        # Instantiate a TableServiceClient using a connection string

        # [START batching]
        from azure.data.tables.aio import TableClient
        from azure.data.tables import TableTransactionError
        from azure.core.exceptions import ResourceExistsError

        self.table_client = TableClient.from_connection_string(
            conn_str=self.connection_string, table_name=self.table_name
        )

        try:
            await self.table_client.create_table()
            print("Created table")
        except ResourceExistsError:
            print("Table already exists")

        await self._create_entities()

        operations = [
            ("create", self.entity1),
            ("delete", self.entity2),
            ("upsert", self.entity3),
            ("update", self.entity4, {"mode": "replace"}),
        ]
        try:
            await self.table_client.submit_transaction(operations) # type: ignore[arg-type]
        except TableTransactionError as e:
            print("There was an error with the transaction operation")
            print("Error: {}".format(e))
        # [END batching]

    async def clean_up(self):
        await self.table_client.delete_table()
        await self.table_client.__aexit__()


async def main():
    sample = CreateClients()
    await sample.sample_transaction()
    await sample.clean_up()


if __name__ == "__main__":
    asyncio.run(main())