azure.data.tables.aio package

class azure.data.tables.aio.TableClient(account_url: str, table_name: str, credential=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, 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.

async create_entity(entity: Union[TableEntity, Dict[str, str]], **kwargs: Any) → Dict[str, str][source]

Insert entity in a table. :param entity: The properties for the table entity. :type entity: dict[str, str] :return: Dictionary of operation metadata returned from service :rtype: dict[str,str] :raises: ~azure.core.exceptions.HttpResponseError

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. :return: Dictionary of operation metadata returned from service :rtype: dict[str,str] :raises: ~azure.core.exceptions.HttpResponseError

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. :param partition_key: The partition key of the entity. :type partition_key: str :param row_key: The row key of the entity. :type row_key: str :keyword str etag: Etag of the entity :keyword ~azure.core.MatchConditions match_condition: MatchCondition :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError

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]

Creates a new table under the given account. :return: None :rtype: None

Example:

Deleting a table from the TableClient object.
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: 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]

Queries entities in a table. :param partition_key: The partition key of the entity. :type partition_key: str :param row_key: The row key of the entity. :type row_key: str :return: TableEntity mapping str to azure.data.tables.EntityProperty :rtype: ~azure.data.tables.TableEntity :raises: ~azure.core.exceptions.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. :return: Dictionary of SignedIdentifiers :rtype: dict[str,~azure.data.tables.AccessPolicy] :raises: ~azure.core.exceptions.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 ItemPaged

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

Returns

Query of table entities

Return type

AsyncItemPaged[TableEntity]

Raises

~azure.core.exceptions.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 ItemPaged

  • list[str]] select (Union[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

ItemPaged[TableEntity]

Raises

~azure.core.exceptions.HttpResponseError

Example:

Querying entities from a TableClient
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
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

~azure.core.exceptions.HttpResponseError

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

Update entity in a table. :param mode: Merge or Replace entity :type mode: ~azure.data.tables.UpdateMode :param entity: The properties for the table entity. :type entity: dict[str, str] :param partition_key: The partition key of the entity. :type partition_key: str :param row_key: The row key of the entity. :type row_key: str :param etag: Etag of the entity :type etag: str :param match_condition: MatchCondition :type match_condition: ~azure.core.MatchConditions :return: Dictionary of operation metadata returned from service :rtype: dict[str,str] :raises: ~azure.core.exceptions.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[TableEntity, Dict[str,str]], mode: UpdateMode = <UpdateMode.MERGE: 'merge'>, **kwargs: Any) → Dict[str, str][source]

Update/Merge or Insert entity into table. :param mode: Merge or Replace and Insert on fail :type mode: ~azure.data.tables.UpdateMode :param entity: The properties for the table entity. :type entity: dict[str, str] :return: Dictionary of operation metadata returned from service :rtype: dict[str,str] :raises: ~azure.core.exceptions.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: Union[str, TokenCredential] = 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.

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
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

~azure.core.exceptions.HttpResponseError

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

Raises

~azure.core.exceptions.HttpResponseError

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 = TableServiceClient.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]

Creates a new table under the given account.

Parameters

table_name (str) – The Table name.

Returns

None

Return type

~None

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

~azure.core.exceptions.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 callable cls

A custom type or function that will be passed the direct response

return

TableServiceStats, or the result of cls(response)

rtype

~azure.data.tables.models.TableServiceStats

raises

~azure.core.exceptions.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

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

Returns

AsyncItemPaged

Return type

~AsyncItemPaged[TableItem]

Raises

~azure.core.exceptions.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=W0622, **kwargs: Any) → AsyncItemPaged[TableItem][source]

Queries tables under the given account. :param filter: Specify a filter to return certain tables :type filter: str :keyword int results_per_page: Number of tables per page in return ItemPaged :keyword Union[str, list(str)] select: Specify desired properties of a table to return certain tables :keyword dict parameters: Dictionary for formatting query with additional, user defined parameters :return: A query of tables :rtype: AsyncItemPaged[TableItem] :raises: ~azure.core.exceptions.HttpResponseError

Example:

Querying tables in an account given specific parameters
        # Query for "table1" in the tables created
        table_name = "mytable1"
        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

~azure.core.exceptions.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().