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

        # [START batching]
        from azure.data.tables.aio import TableClient
        from azure.data.tables import UpdateMode, BatchErrorException
        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()

        batch = self.table_client.create_batch()
        batch.create_entity(self.entity1)
        batch.delete_entity(partition_key=self.entity2['PartitionKey'],
                            row_key=self.entity2['RowKey'])
        batch.upsert_entity(self.entity3)
        batch.update_entity(self.entity4, mode=UpdateMode.REPLACE)
        try:
            await self.table_client.send_batch(batch)
        except BatchErrorException as e:
            print("There was an error with the batch operation")
            print("Error: {}".format(e))
示例#2
0
 async def create_table_client(self):
     # Instantiate a TableServiceClient using a connection string
     # [START create_table_client]
     from azure.data.tables.aio import TableClient
     table_client = TableClient.from_connection_string(
         conn_str=self.connection_string, table_name="tableName")
     print("Table name: {}".format(table_client.table_name))
    async def insert_random_entities(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import ResourceExistsError
        brands = ["Crayola", "Sharpie", "Chameleon"]
        colors = ["red", "blue", "orange", "yellow"]
        names = ["marker", "pencil", "pen"]
        entity_template = {
            "PartitionKey": "pk",
            "RowKey": "row",
        }

        table_client = TableClient.from_connection_string(self.connection_string, self.table_name)
        async with table_client:
            try:
                await table_client.create_table()
            except ResourceExistsError:
                print("Table already exists")

            for i in range(25):
                e = copy.deepcopy(entity_template)
                e["RowKey"] += str(i)
                e["Name"] = random.choice(names)
                e["Brand"] = random.choice(brands)
                e["Color"] = random.choice(colors)
                e["Value"] = random.randint(0, 100)
                await table_client.create_entity(entity=e)
示例#4
0
    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)
        except TableTransactionError as e:
            print("There was an error with the transaction operation")
            print("Error: {}".format(e))
    async def create_and_get_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient
        table = TableClient.from_connection_string(
            self.connection_string, table_name=self.table_base + "create")

        async with table:
            await table.create_table()

            my_entity = {
                'PartitionKey': 'color',
                'RowKey': 'crayola',
                'text': 'Marker',
                'color': 'Purple',
                'price': '5'
            }
            try:
                created_entity = await table.create_entity(entity=my_entity)
                print("Created entity: {}".format(created_entity))

                # [START get_entity]
                # Get Entity by partition and row key
                got_entity = await table.get_entity(
                    partition_key=my_entity['PartitionKey'],
                    row_key=my_entity['RowKey']
                )
                print("Received entity: {}".format(got_entity))
                # [END get_entity]

            finally:
                await table.delete_table()
    async def list_all_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient
        table = TableClient.from_connection_string(
            self.connection_string, table_name=self.table_base + "list")

        # Create the table
        async with table:
            await table.create_table()

            entity = {'PartitionKey': 'color2', 'RowKey': 'sharpie', 'text': 'Marker', 'color': 'Purple', 'price': '5'}
            entity1 = {'PartitionKey': 'color2', 'RowKey': 'crayola', 'text': 'Marker', 'color': 'Red', 'price': '3'}

            try:
                # Create entities
                await table.create_entity(entity=entity)
                await table.create_entity(entity=entity1)
                # [START list_entities]
                # Query the entities in the table
                entities = []
                async for e in table.list_entities():
                    entities.append(e)

                for i, entity in enumerate(entities):
                    print("Entity #{}: {}".format(entity, i))
                # [END list_entities]

            finally:
                await table.delete_table()
    async def create_and_get_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient

        table = TableClient.from_connection_string(self.connection_string,
                                                   table_name=self.table_base +
                                                   "create")

        async with table:
            await table.create_table()

            my_entity = {
                "PartitionKey": "color",
                "RowKey": "crayola",
                "text": "Marker",
                "color": "Purple",
                "price": "5",
            }
            try:
                created_entity = await table.create_entity(entity=my_entity)
                print("Created entity: {}".format(created_entity))

                # [START get_entity]
                # Get Entity by partition and row key
                got_entity = await table.get_entity(
                    partition_key=my_entity["PartitionKey"],
                    row_key=my_entity["RowKey"])
                print("Received entity: {}".format(got_entity))
                # [END get_entity]

            finally:
                await table.delete_table()
示例#8
0
    async def delete_from_table_client(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import HttpResponseError

        # [START delete_from_table_client]
        async with TableClient.from_connection_string(
            conn_str=self.connection_string,
            table_name=self.table_name) as table_client:
            await table_client.delete_table()
            print("Deleted table {}!".format(self.table_name))
    async def create_from_table_client(self):
        from azure.data.tables.aio import TableClient

        # [START create_from_table_client]
        async with TableClient.from_connection_string(conn_str=self.connection_string, table_name=self.table_name) as table_client:
            try:
                table_item = await table_client.create_table()
                print("Created table {}!".format(table_item.table_name))
            except ResourceExistsError:
                print("Table already exists")
    async def delete_from_table_client(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import ResourceNotFoundError

        # [START delete_from_table_client]
        async with TableClient.from_connection_string(conn_str=self.connection_string, table_name=self.table_name) as table_client:
            try:
                await table_client.delete_table()
                print("Deleted table {}!".format(self.table_name))
            except ResourceNotFoundError:
                print("Table could not be found")
    async def update_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient
        from azure.data.tables import UpdateMode
        table = TableClient.from_connection_string(
            self.connection_string, table_name=self.table_base + "update")

        # Create the table and Table Client
        async with table:
            await table.create_table()

            entity = {'PartitionKey': 'color', 'RowKey': 'sharpie', 'text': 'Marker', 'color': 'Purple', 'price': '5'}
            entity1 = {'PartitionKey': 'color2', 'RowKey': 'crayola', 'text': 'Marker', 'color': 'Red', 'price': '3'}

            try:
                # Create entities
                await table.create_entity(entity=entity)
                created = await table.get_entity(partition_key=entity["PartitionKey"], row_key=entity["RowKey"])

                # [START upsert_entity]
                # Try Replace and then Insert on Fail
                insert_entity = await table.upsert_entity(mode=UpdateMode.REPLACE, entity=entity1)
                print("Inserted entity: {}".format(insert_entity))

                # Try merge, and merge since already in table
                created['text'] = "NewMarker"
                merged_entity = await table.upsert_entity(mode=UpdateMode.MERGE, entity=entity)
                print("Merged entity: {}".format(merged_entity))
                # [END upsert_entity]

                # [START update_entity]
                # Update the entity
                created['text'] = "NewMarker"
                await table.update_entity(mode=UpdateMode.REPLACE, entity=created)

                # Get the replaced entity
                replaced = await table.get_entity(
                    partition_key=created['PartitionKey'], row_key=created['RowKey'])
                print("Replaced entity: {}".format(replaced))

                # Merge the entity
                replaced['color'] = "Blue"
                await table.update_entity(mode=UpdateMode.MERGE, entity=replaced)

                # Get the merged entity
                merged = await table.get_entity(
                    partition_key=replaced['PartitionKey'], row_key=replaced['RowKey'])
                print("Merged entity: {}".format(merged))
                # [END update_entity]

            finally:
                await table.delete_table()
示例#12
0
    def test_create_client_for_cosmos_emulator(self):
        emulator_credential = AzureNamedKeyCredential(
            'localhost', self.tables_primary_cosmos_account_key)
        emulator_connstr = "DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey={};TableEndpoint=http://localhost:8902/;".format(
            self.tables_primary_cosmos_account_key)

        client = TableServiceClient.from_connection_string(emulator_connstr)
        assert client.url == "http://localhost:8902"
        assert client.account_name == 'localhost'
        assert client.credential.named_key.name == 'localhost'
        assert client.credential.named_key.key == self.tables_primary_cosmos_account_key
        assert client._cosmos_endpoint

        client = TableServiceClient("http://localhost:8902/",
                                    credential=emulator_credential)
        assert client.url == "http://localhost:8902"
        assert client.account_name == 'localhost'
        assert client.credential.named_key.name == 'localhost'
        assert client.credential.named_key.key == self.tables_primary_cosmos_account_key
        assert client._cosmos_endpoint

        table = TableClient.from_connection_string(emulator_connstr,
                                                   'tablename')
        assert table.url == "http://localhost:8902"
        assert table.account_name == 'localhost'
        assert table.table_name == 'tablename'
        assert table.credential.named_key.name == 'localhost'
        assert table.credential.named_key.key == self.tables_primary_cosmos_account_key
        assert table._cosmos_endpoint

        table = TableClient("http://localhost:8902/",
                            "tablename",
                            credential=emulator_credential)
        assert table.url == "http://localhost:8902"
        assert table.account_name == 'localhost'
        assert table.table_name == 'tablename'
        assert table.credential.named_key.name == 'localhost'
        assert table.credential.named_key.key == self.tables_primary_cosmos_account_key
        assert table._cosmos_endpoint

        table = TableClient.from_table_url(
            "http://localhost:8902/Tables('tablename')",
            credential=emulator_credential)
        assert table.url == "http://localhost:8902"
        assert table.account_name == 'localhost'
        assert table.table_name == 'tablename'
        assert table.credential.named_key.name == 'localhost'
        assert table.credential.named_key.key == self.tables_primary_cosmos_account_key
        assert table._cosmos_endpoint
示例#13
0
    async def list_all_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient

        table = TableClient.from_connection_string(self.connection_string,
                                                   table_name=self.table_base +
                                                   "list")

        # Create the table
        async with table:
            await table.create_table()

            entity = {
                "PartitionKey": "color2",
                "RowKey": "sharpie",
                "text": "Marker",
                "color": "Purple",
                "price": 5.99,
                "inventory": 42,
                "product_id": uuid4(),
            }
            entity1 = {
                "PartitionKey": "color2",
                "RowKey": "crayola",
                "text": "Marker",
                "color": "Red",
                "price": 3.99,
                "inventory": 42,
                "product_id": uuid4(),
            }

            try:
                # Create entities
                await table.create_entity(entity=entity)
                await table.create_entity(entity=entity1)
                # [START list_entities]
                # Query the entities in the table
                i = 0
                async for entity in table.list_entities():
                    print("Entity #{}: {}".format(i, entity))
                    i += 1
                # [END list_entities]

            finally:
                await table.delete_table()
    async def create_entity(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import ResourceExistsError, HttpResponseError

        table_client = TableClient.from_connection_string(self.connection_string, self.table_name)
        # Create a table in case it does not already exist
        # [START create_entity]
        async with table_client:
            try:
                await table_client.create_table()
            except HttpResponseError:
                print("Table already exists")

            try:
                entity = await table_client.create_entity(entity=self.entity)
                print(entity)
            except ResourceExistsError:
                print("Entity already exists")
    async def sample_query_entities_values(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import HttpResponseError

        print("Entities with 25 < Value < 50")
        # [START query_entities]
        async with TableClient.from_connection_string(self.connection_string, self.table_name) as table_client:
            try:
                parameters = {u"lower": 25, u"upper": 50}
                name_filter = u"Value gt @lower and Value lt @upper"
                queried_entities = table_client.query_entities(
                    query_filter=name_filter, select=[u"Value"], parameters=parameters
                )

                async for entity_chosen in queried_entities:
                    print(entity_chosen)

            except HttpResponseError as e:
                print(e.message)
    async def sample_query_entities_multiple_params(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import HttpResponseError

        print("Entities with name: marker and brand: Crayola")
        # [START query_entities]
        async with TableClient.from_connection_string(self.connection_string, self.table_name) as table_client:
            try:
                parameters = {u"name": u"marker", u"brand": u"Crayola"}
                name_filter = u"Name eq @name and Brand eq @brand"
                queried_entities = table_client.query_entities(
                    query_filter=name_filter, select=[u"Brand", u"Color"], parameters=parameters
                )

                async for entity_chosen in queried_entities:
                    print(entity_chosen)

            except HttpResponseError as e:
                print(e.message)
    async def sample_query_entities(self):
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import HttpResponseError

        print("Entities with name: marker")
        table_client = TableClient.from_connection_string(self.connection_string, self.table_name)
        # [START query_entities]
        async with table_client:
            try:
                parameters = {
                    u"name": u"marker"
                }
                name_filter = u"Name eq @name"
                async for entity_chosen in table_client.query_entities(
                    filter=name_filter, select=[u"Brand",u"Color"], parameters=parameters):
                    print(entity_chosen)

            except HttpResponseError as e:
                pass
    async def _insert_random_entities(self):
        from azure.data.tables.aio import TableClient
        brands = ["Crayola", "Sharpie", "Chameleon"]
        colors = ["red", "blue", "orange", "yellow"]
        names = ["marker", "pencil", "pen"]
        entity_template = {
            "PartitionKey": "pk",
            "RowKey": "row",
        }

        table_client = TableClient.from_connection_string(
            self.connection_string, self.table_name)
        await table_client.create_table()

        for i in range(10):
            e = copy.deepcopy(entity_template)
            e["RowKey"] += str(i)
            e["Name"] = random.choice(names)
            e["Brand"] = random.choice(brands)
            e["Color"] = random.choice(colors)
            await table_client.create_entity(entity=e)
    async def sample_query_entities(self):
        await self._insert_random_entities()
        from azure.data.tables.aio import TableClient
        from azure.core.exceptions import HttpResponseError

        table_client = TableClient.from_connection_string(
            self.connection_string, self.table_name)
        # [START query_entities]
        async with table_client:
            try:
                entity_name = "marker"
                name_filter = "Name eq '{}'".format(entity_name)

                async for entity_chosen in table_client.query_entities(
                        filter=name_filter, select=["Brand", "Color"]):
                    print(entity_chosen)

            except HttpResponseError as e:
                pass
            # [END query_entities]
            finally:
                await table_client.delete_table()
示例#20
0
    async def create_and_get_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient

        table = TableClient.from_connection_string(self.connection_string,
                                                   table_name=self.table_base +
                                                   "create")

        async with table:
            await table.create_table()

            my_entity = {
                "PartitionKey": "color",
                "RowKey": "brand",
                "text": "Marker",
                "color": "Purple",
                "price": 4.99,
                "last_updated": datetime.today(),
                "product_id": uuid4(),
                "inventory_count": 42,
                "barcode": b"135aefg8oj0ld58"
            }

            try:
                created_entity = await table.create_entity(entity=my_entity)
                print("Created entity: {}".format(created_entity))

                # [START get_entity]
                # Get Entity by partition and row key
                got_entity = await table.get_entity(
                    partition_key=my_entity["PartitionKey"],
                    row_key=my_entity["RowKey"])
                print("Received entity: {}".format(got_entity))
                # [END get_entity]

            finally:
                await table.delete_table()
    async def update_entities(self):
        # Instantiate a table service client
        from azure.data.tables.aio import TableClient
        from azure.data.tables import UpdateMode

        table = TableClient.from_connection_string(self.connection_string,
                                                   table_name=self.table_base +
                                                   "update")

        # Create the table and Table Client
        async with table:
            await table.create_table()

            entity = {
                "PartitionKey": "color",
                "RowKey": "sharpie",
                "text": "Marker",
                "color": "Purple",
                "price": "5"
            }
            entity1 = {
                "PartitionKey": "color2",
                "RowKey": "crayola",
                "text": "Marker",
                "color": "Red",
                "price": "3"
            }

            try:
                # Create entities
                await table.create_entity(entity=entity)
                created = await table.get_entity(
                    partition_key=entity["PartitionKey"],
                    row_key=entity["RowKey"])

                # [START upsert_entity]
                # Try Replace and insert on fail
                insert_entity = await table.upsert_entity(
                    mode=UpdateMode.REPLACE, entity=entity1)
                print("Inserted entity: {}".format(insert_entity))

                created["text"] = "NewMarker"
                merged_entity = await table.upsert_entity(
                    mode=UpdateMode.MERGE, entity=entity)
                print("Merged entity: {}".format(merged_entity))
                # [END upsert_entity]

                # [START update_entity]
                # Update the entity
                created["text"] = "NewMarker"
                await table.update_entity(mode=UpdateMode.REPLACE,
                                          entity=created)

                # Get the replaced entity
                replaced = await table.get_entity(
                    partition_key=created["PartitionKey"],
                    row_key=created["RowKey"])
                print("Replaced entity: {}".format(replaced))

                # Merge the entity
                replaced["color"] = "Blue"
                await table.update_entity(mode=UpdateMode.MERGE,
                                          entity=replaced)

                # Get the merged entity
                merged = await table.get_entity(
                    partition_key=replaced["PartitionKey"],
                    row_key=replaced["RowKey"])
                print("Merged entity: {}".format(merged))
                # [END update_entity]

            finally:
                await table.delete_table()
示例#22
0
    async def test_create_client_for_azurite(self):
        azurite_credential = AzureNamedKeyCredential(
            "myaccount", self.tables_primary_storage_account_key)
        http_connstr = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey={};TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;".format(
            self.tables_primary_storage_account_key)
        https_connstr = "DefaultEndpointsProtocol=https;AccountName=devstoreaccount1;AccountKey={};TableEndpoint=https://127.0.0.1:10002/devstoreaccount1;".format(
            self.tables_primary_storage_account_key)
        account_url = "https://127.0.0.1:10002/myaccount"
        client = TableServiceClient(account_url, credential=azurite_credential)
        assert client.account_name == "myaccount"
        assert client.url == "https://127.0.0.1:10002/myaccount"
        assert client._location_mode == "primary"
        assert client._secondary_endpoint == "https://127.0.0.1:10002/myaccount-secondary"
        assert client.credential.named_key.key == azurite_credential.named_key.key
        assert client.credential.named_key.name == azurite_credential.named_key.name
        assert not client._cosmos_endpoint

        client = TableServiceClient.from_connection_string(http_connstr)
        assert client.account_name == "devstoreaccount1"
        assert client.url == "http://127.0.0.1:10002/devstoreaccount1"
        assert client._location_mode == "primary"
        assert client._secondary_endpoint == "http://127.0.0.1:10002/devstoreaccount1-secondary"
        assert client.credential.named_key.key == self.tables_primary_storage_account_key
        assert client.credential.named_key.name == "devstoreaccount1"
        assert not client._cosmos_endpoint

        client = TableServiceClient.from_connection_string(https_connstr)
        assert client.account_name == "devstoreaccount1"
        assert client.url == "https://127.0.0.1:10002/devstoreaccount1"
        assert client._location_mode == "primary"
        assert client._secondary_endpoint == "https://127.0.0.1:10002/devstoreaccount1-secondary"
        assert client.credential.named_key.key == self.tables_primary_storage_account_key
        assert client.credential.named_key.name == "devstoreaccount1"
        assert not client._cosmos_endpoint

        table = TableClient(account_url,
                            "tablename",
                            credential=azurite_credential)
        assert table.account_name == "myaccount"
        assert table.table_name == "tablename"
        assert table.url == "https://127.0.0.1:10002/myaccount"
        assert table._location_mode == "primary"
        assert table._secondary_endpoint == "https://127.0.0.1:10002/myaccount-secondary"
        assert table.credential.named_key.key == azurite_credential.named_key.key
        assert table.credential.named_key.name == azurite_credential.named_key.name
        assert not table._cosmos_endpoint

        table = TableClient.from_connection_string(http_connstr, "tablename")
        assert table.account_name == "devstoreaccount1"
        assert table.table_name == "tablename"
        assert table.url == "http://127.0.0.1:10002/devstoreaccount1"
        assert table._location_mode == "primary"
        assert table._secondary_endpoint == "http://127.0.0.1:10002/devstoreaccount1-secondary"
        assert table.credential.named_key.key == self.tables_primary_storage_account_key
        assert table.credential.named_key.name == "devstoreaccount1"
        assert not table._cosmos_endpoint

        table = TableClient.from_connection_string(https_connstr, "tablename")
        assert table.account_name == "devstoreaccount1"
        assert table.table_name == "tablename"
        assert table.url == "https://127.0.0.1:10002/devstoreaccount1"
        assert table._location_mode == "primary"
        assert table._secondary_endpoint == "https://127.0.0.1:10002/devstoreaccount1-secondary"
        assert table.credential.named_key.key == self.tables_primary_storage_account_key
        assert table.credential.named_key.name == "devstoreaccount1"
        assert not table._cosmos_endpoint

        table_url = "https://127.0.0.1:10002/myaccount/Tables('tablename')"
        table = TableClient.from_table_url(table_url,
                                           credential=azurite_credential)
        assert table.account_name == "myaccount"
        assert table.table_name == "tablename"
        assert table.url == "https://127.0.0.1:10002/myaccount"
        assert table._location_mode == "primary"
        assert table._secondary_endpoint == "https://127.0.0.1:10002/myaccount-secondary"
        assert table.credential.named_key.key == azurite_credential.named_key.key
        assert table.credential.named_key.name == azurite_credential.named_key.name
        assert not table._cosmos_endpoint
 async def clean_up(self):
     print("cleaning up")
     from azure.data.tables.aio import TableClient
     async with TableClient.from_connection_string(self.connection_string, self.table_name) as table_client:
         await table_client.delete_table()