azure.data.tables.aio package

class azure.data.tables.aio.TableClient(account_url: str, table_name: str, credential: Optional[str] = None, **kwargs: Any)[source]
Variables

account_name (str) – Name of the storage account (Cosmos or Azure)

Create TableClient from a Credential.

Parameters
  • account_url (str) – A url to an Azure Storage account.

  • table_name (str) – The table name.

  • credential (str) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token, or the connection string already has shared access key values. The value can be a SAS token string or an account shared access key.

Returns

None

async close()

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

create_batch(**kwargs: Dict[str, Any]) → azure.data.tables.aio._table_batch_async.TableBatchOperations[source]

Create a Batching object from a Table Client

Returns

Object containing requests and responses

Return type

TableBatchOperations

Example:

Creating and adding an entity to a Table
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))
async create_entity(entity: Union[azure.data.tables._entity.TableEntity, Dict[str, str]], **kwargs: Any) → Dict[str, str][source]

Insert entity in a table.

Parameters

entity (TableEntity or dict[str,str]) – The properties for the table entity.

Returns

Dictionary mapping operation metadata returned from the service

Return type

dict[str,str]

Raises

ResourceExistsError – If the entity already exists

Example:

Adding an entity to a Table
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 create_table(**kwargs: Any) → Dict[str, str][source]

Creates a new table under the given account.

Returns

Dictionary of operation metadata returned from service

Return type

dict[str,str]

Raises

ResourceExistsError – If the table already exists

Example:

Creating a table from the TableClient object.
async with TableServiceClient.from_connection_string(self.connection_string) as table_service_client:
    try:
        table_item = await table_service_client.create_table(table_name=self.table_name)
        print("Created table {}!".format(table_item.table_name))
    except ResourceExistsError:
        print("Table already exists")
async delete_entity(partition_key: str, row_key: str, **kwargs: Any)None[source]

Deletes the specified entity in a table.

Parameters
  • partition_key (str) – The partition key of the entity.

  • row_key (str) – The row key of the entity.

Keyword Arguments
Returns

None

Return type

None

Raises

ResourceNotFoundError – If the table does not exist

Example:

Adding an entity to a Table
async with table_client:
    try:
        resp = await table_client.create_entity(entity=self.entity)
    except ResourceExistsError:
        print("Entity already exists!")

    try:
        await table_client.delete_entity(
            row_key=self.entity["RowKey"],
            partition_key=self.entity["PartitionKey"]
        )
        print("Successfully deleted!")
    except ResourceNotFoundError:
        print("Entity does not exists")
async delete_table(**kwargs: Any)None[source]

Deletes the table under the current account.

Returns

None

Return type

None

Raises

ResourceNotFoundError

Example:

Deleting a table from the TableClient object.
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")
classmethod from_connection_string(conn_str: str, table_name: str, **kwargs: Any) → azure.data.tables.aio._table_client_async.TableClient[source]

Create TableClient from a Connection string.

Parameters
  • conn_str (str) – A connection string to an Azure Storage or Cosmos account.

  • table_name (str) – The table name.

Returns

A table client.

Return type

TableClient

Example:

Creating the TableClient from a connection string.
from azure.data.tables.aio import TableClient
async with TableClient.from_connection_string(conn_str=self.connection_string, table_name="tableName") as table_client:
    print("Table name: {}".format(table_client.table_name))
classmethod from_table_url(table_url: str, credential: Optional[Any] = None, **kwargs: Any) → TableClient[source]

A client to interact with a specific Table.

Parameters
  • table_url (str) – The full URI to the table, including SAS token if used.

  • credential (str) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an account shared access key.

Returns

A table client.

Return type

TableClient

async get_entity(partition_key: str, row_key: str, **kwargs: Any) → azure.data.tables._entity.TableEntity[source]

Get a single entity in a table.

Parameters
  • partition_key (str) – The partition key of the entity.

  • row_key (str) – The row key of the entity.

Returns

Dictionary mapping operation metadata returned from the service

Return type

TableEntity

Raises

HttpResponseError

Example:

Getting an entity from PartitionKey and RowKey
        # 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))
async get_table_access_policy(**kwargs: Any)dict[str, AccessPolicy][source]

Retrieves details about any stored access policies specified on the table that may be used with Shared Access Signatures.

Returns

Dictionary of SignedIdentifiers

Return type

dict[str,AccessPolicy]

Raises

HttpResponseError

list_entities(**kwargs: Any)azure.core.async_paging.AsyncItemPaged[azure.data.tables._entity.TableEntity][source]

Lists entities in a table.

Keyword Arguments
  • results_per_page (int) – Number of entities per page in return AsyncItemPaged

  • select (str or list[str]) – Specify desired properties of an entity to return certain entities

Returns

Query of table entities

Return type

AsyncItemPaged[TableEntity]

Raises

HttpResponseError

Example:

Querying entities from a TableClient
        # 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))
query_entities(filter: str, **kwargs)azure.core.async_paging.AsyncItemPaged[azure.data.tables._entity.TableEntity][source]

Lists entities in a table.

Parameters

filter (str) – Specify a filter to return certain entities

Keyword Arguments
  • results_per_page (int) – Number of entities per page in return AsyncItemPaged

  • select (str or list[str]) – Specify desired properties of an entity to return certain entities

  • parameters (dict) – Dictionary for formatting query with additional, user defined parameters

Returns

Query of table entities

Return type

AsyncItemPaged[TableEntity]

Raises

HttpResponseError

Example:

Querying entities from a TableClient
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 send_batch(batch: azure.data.tables.aio._table_batch_async.TableBatchOperations, **kwargs: Dict[Any, str]) → azure.data.tables._models.BatchTransactionResult[source]

Commit a TableBatchOperations to send requests to the server

Returns

Object containing requests and responses

Return type

BatchTransactionResult

Raises

BatchErrorException

Example:

Using batches to send multiple requests at once
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))
async set_table_access_policy(signed_identifiers: dict[str, AccessPolicy], **kwargs)None[source]

Sets stored access policies for the table that may be used with Shared Access Signatures.

Parameters

signed_identifiers (dict[str,AccessPolicy]) –

Returns

None

Return type

None

Raises

HttpResponseError

async update_entity(entity: Union[azure.data.tables._entity.TableEntity, Dict[str, str]], mode: azure.data.tables._models.UpdateMode = <UpdateMode.MERGE: 'merge'>, **kwargs: Any) → Dict[str, str][source]

Update entity in a table.

Parameters
  • entity (dict[str, str]) – The properties for the table entity.

  • mode (UpdateMode) – Merge or Replace entity

Keyword Arguments
  • partition_key (str) – The partition key of the entity.

  • row_key (str) – The row key of the entity.

  • etag (str) – Etag of the entity

  • match_condition (MatchConditions) – MatchCondition

Returns

Dictionary of operation metadata returned from service

Return type

dict[str,str]

Raises

HttpResponseError

Example:

Querying entities from a TableClient
        # 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))
async upsert_entity(entity: Union[azure.data.tables._entity.TableEntity, Dict[str, str]], mode: azure.data.tables._models.UpdateMode = <UpdateMode.MERGE: 'merge'>, **kwargs: Any) → Dict[str, str][source]

Update/Merge or Insert entity into table.

Parameters
Returns

Dictionary mapping operation metadata returned from the service

Return type

dict[str,str]

Raises

HttpResponseError

Example:

Update/Merge or Insert an entity into a table
        # 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))
property api_version

The version of the Storage API used for requests.

Type

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Type

str

property url

The full endpoint URL to this entity, including SAS token if used.

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode().

class azure.data.tables.aio.TableServiceClient(account_url: str, credential: Optional[str] = None, **kwargs: Any)[source]

A client to interact with the Table Service at the account level.

This client provides operations to retrieve and configure the account properties as well as list, create and delete tables within the account. For operations relating to a specific queue, a client for this entity can be retrieved using the get_table_client() function.

Parameters
  • account_url (str) – The URL to the table service endpoint. Any other entities included in the URL path (e.g. queue) will be discarded. This URL can be optionally authenticated with a SAS token.

  • credential (str) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an account shared access key.

  • credential – The credentials with which to authenticate. This is optional if the account URL already has a SAS token, or the connection string already has shared access key values. The value can be a SAS token string or an account shared access key.

Keyword Arguments
  • api_version (str) – The Storage API version to use for requests. Default value is ‘2019-07-07’. Setting to an older version may result in reduced feature compatibility.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

Example:

Creating the tableServiceClient with an account url and credential.
from azure.data.tables.aio import TableServiceClient
async with TableServiceClient.from_connection_string(conn_str=self.connection_string) as table_service:
    properties = await table_service.get_service_properties()
    print("Shared Key: {}".format(properties))
Creating the tableServiceClient with Shared Access Signature.
from azure.data.tables.aio import TableServiceClient

# Create a SAS token to use for authentication of a client
from azure.data.tables import generate_account_sas, ResourceTypes, AccountSasPermissions
print("Account name: {}".format(self.account_name))
sas_token = generate_account_sas(
    self.account_name,
    self.access_key,
    resource_types=ResourceTypes(service=True),
    permission=AccountSasPermissions(read=True),
    expiry=datetime.utcnow() + timedelta(hours=1)
)

async with TableServiceClient(account_url=self.account_url, credential=sas_token) as token_auth_table_service:
    properties = await token_auth_table_service.get_service_properties()
    print("Shared Access Signature: {}".format(properties))
async close()

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

async create_table(table_name: str, **kwargs: Any) → azure.data.tables.aio._table_client_async.TableClient[source]

Creates a new table under the given account.

Parameters
  • headers

  • table_name (Table) – The Table name.

Returns

TableClient, or the result of cls(response)

Return type

TableClient or None

Raises

ResourceExistsError

Example:

Creating a table from TableServiceClient.
async with TableServiceClient.from_connection_string(self.connection_string) as table_service_client:
    try:
        table_item = await table_service_client.create_table(table_name=self.table_name)
        print("Created table {}!".format(table_item.table_name))
    except ResourceExistsError:
        print("Table already exists")
async create_table_if_not_exists(table_name: str, **kwargs: Any) → azure.data.tables.aio._table_client_async.TableClient[source]

Creates a new table if it does not currently exist. If the table currently exists, the current table is returned.

Parameters

table_name (str) – The Table name.

Returns

TableClient

Return type

TableClient

Example:

Creating a table if it does not already exist
async with TableServiceClient.from_connection_string(self.connection_string) as table_service_client:
    table_item = await table_service_client.create_table_if_not_exists(table_name=self.table_name)
    print("Table name: {}".format(table_item.table_name))
async delete_table(table_name: str, **kwargs: Any)None[source]

Deletes the table under the current account

Parameters

table_name (str) – The Table name.

Returns

None

Return type

None

Raises

ResourceNotFoundError

Example:

Deleting a table
async with TableServiceClient.from_connection_string(self.connection_string) as table_service_client:
    try:
        await table_service_client.delete_table(table_name=self.table_name)
        print("Deleted table {}!".format(self.table_name))
    except ResourceNotFoundError:
        print("Table could not be found")
classmethod from_connection_string(conn_str: any, **kwargs: Any) → azure.data.tables.aio._table_service_client_async.TableServiceClient[source]

Create TableServiceClient from a Connection String.

Parameters

conn_str (str) – A connection string to an Azure Storage or Cosmos account.

Returns

A Table service client.

Return type

TableServiceClient

Example:

Creating the tableServiceClient from a connection string
from azure.data.tables.aio import TableServiceClient
async with TableServiceClient.from_connection_string(conn_str=self.connection_string) as table_service:
    properties = await table_service.get_service_properties()
    print("Connection String: {}".format(properties))
async get_service_properties(**kwargs)dict[str, Any][source]

Gets the properties of an account’s Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

TableServiceProperties, or the result of cls(response)

Return type

TableServiceProperties

Raises

HttpResponseError

async get_service_stats(**kwargs)dict[str, object][source]

Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

Dictionary of service stats

Return type

TableServiceStats

Raises

HttpResponseError

get_table_client(table_name: str, **kwargs: Optional[Any]) → azure.data.tables.aio._table_client_async.TableClient[source]

Get a client to interact with the specified table.

The table need not already exist.

Parameters

table (str or TableProperties) – The queue. This can either be the name of the queue, or an instance of QueueProperties.

Returns

A TableClient object.

Return type

TableClient

list_tables(**kwargs: Any)azure.core.async_paging.AsyncItemPaged[azure.data.tables._models.TableItem][source]

Queries tables under the given account.

Keyword Arguments
  • results_per_page (int) – Number of tables per page in return ItemPaged

  • select (str or list[str]) – Specify desired properties of a table to return certain tables

Returns

AsyncItemPaged

Return type

AsyncItemPaged[TableItem]

Raises

HttpResponseError

Example:

Listing all tables in an account
        # List all the tables in the service
        print("Listing tables:")
        async for table in table_service.list_tables():
            print("\t{}".format(table.table_name))
query_tables(filter: str pylint: disable=redefined-builtin, **kwargs: Any) → AsyncItemPaged[TableItem][source]

Queries tables under the given account.

Parameters

filter (str) – Specify a filter to return certain tables.

Keyword Arguments
  • results_per_page (int) – Number of tables per page in return ItemPaged

  • select (str or list[str]) – Specify desired properties of a table to return certain tables

  • parameters (dict[str,str]) – Dictionary for formatting query with additional, user defined parameters

Returns

An ItemPaged of tables

Return type

AsyncItemPaged[TableItem]

Raises

HttpResponseError

Example:

Querying tables in an account given specific parameters
        # Query for "table1" in the tables created
        table_name = "mytableasync1"
        name_filter = "TableName eq '{}'".format(table_name)
        print("Queried_tables")
        async for table in table_service.query_tables(filter=name_filter):
            print("\t{}".format(table.table_name))
async set_service_properties(analytics_logging: Optional[TableAnalyticsLogging] = None, hour_metrics: Optional[Metrics] = None, minute_metrics: Optional[Metrics] = None, cors: Optional[CorsRule] = None, **kwargs: Any)None[source]
Sets properties for an account’s Table service endpoint,

including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules.

Parameters
  • analytics_logging (TableAnalyticsLogging) – Properties for analytics

  • hour_metrics (Metrics) – Hour level metrics

  • minute_metrics (Metrics) – Minute level metrics

  • cors (CorsRule) – Cross-origin resource sharing rules

Returns

None

Return type

None

Raises

HttpResponseError

property api_version

The version of the Storage API used for requests.

Type

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Type

str

property url

The full endpoint URL to this entity, including SAS token if used.

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode().