Partilhar via


TableClient Class

A client to interact with a specific Table in an Azure Tables account.

Create TableClient from a Credential.

Inheritance
azure.data.tables.aio._base_client_async.AsyncTablesBaseClient
TableClient

Constructor

TableClient(endpoint: str, table_name: str, *, credential: AzureSasCredential | AzureNamedKeyCredential | AsyncTokenCredential | None = None, api_version: str | None = None, **kwargs: Any)

Parameters

Name Description
endpoint
Required
str

A URL to an Azure Tables account.

table_name
Required
str

The table name.

Keyword-Only Parameters

Name Description
credential

The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be one of AzureNamedKeyCredential (azure-core), AzureSasCredential (azure-core), or an AsyncTokenCredential implementation from azure-identity.

api_version
str or None

Specifies the version of the operation to use for this request. Default value is "2019-02-02".

Variables

Name Description
account_name
str

The name of the Tables account.

table_name
str

The name of the table.

scheme
str

The scheme component in the full URL to the Tables account.

url
str

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

api_version
str

The version of the Storage API used for requests.

credential

The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be one of AzureNamedKeyCredential (azure-core), AzureSasCredential (azure-core), or a AsyncTokenCredential implementation from azure-identity.

Methods

close

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

create_entity

Inserts entity in a table.

create_table

Creates a new table under the given account.

delete_entity
delete_table

Deletes the table under the current account. No error will be raised if the table does not exist.

from_connection_string

Create TableClient from a Connection string.

from_table_url

A client to interact with a specific Table.

get_entity

Gets a single entity in a table.

get_table_access_policy

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

list_entities

Lists entities in a table.

query_entities

Queries entities in a table.

set_table_access_policy

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

submit_transaction

Commits a list of operations as a single transaction.

If any one of these operations fails, the entire transaction will be rejected.

update_entity

Updates an entity in a table.

upsert_entity

Updates (merge or replace) an entity into a table.

close

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

async close() -> None

create_entity

Inserts entity in a table.

async create_entity(entity: TableEntity | Mapping[str, Any], **kwargs) -> Mapping[str, Any]

Parameters

Name Description
entity
Required

The properties for the table entity.

Returns

Type Description

Dictionary mapping operation metadata returned from the service.

Exceptions

Type Description

If the entity already exists

Examples

Creating and adding an entity to a Table


   try:
       resp = await table_client.create_entity(entity=self.entity)
       print(resp)
   except ResourceExistsError:
       print("Entity already exists")

create_table

Creates a new table under the given account.

async create_table(**kwargs) -> TableItem

Returns

Type Description

A TableItem representing the created table.

Exceptions

Type Description

If the entity already exists

Examples

Creating 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:
           table_item = await table_client.create_table()
           print(f"Created table {table_item.name}!")
       except ResourceExistsError:
           print("Table already exists")

delete_entity

async delete_entity(partition_key: str, row_key: str, *, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) -> None

delete_table

Deletes the table under the current account. No error will be raised if the table does not exist.

async delete_table(**kwargs) -> None

Returns

Type Description

None

Exceptions

Type Description

Examples

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:
       await table_client.delete_table()
       print(f"Deleted table {table_client.table_name}!")

from_connection_string

Create TableClient from a Connection string.

from_connection_string(conn_str: str, table_name: str, **kwargs: Any) -> TableClient

Parameters

Name Description
conn_str
Required
str

A connection string to an Azure Tables account.

table_name
Required
str

The table name.

Returns

Type Description

A table client.

Examples

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(f"Table name: {table_client.table_name}")

from_table_url

A client to interact with a specific Table.

from_table_url(table_url: str, *, credential: AzureNamedKeyCredential | AzureSasCredential | None = None, **kwargs: Any) -> TableClient

Parameters

Name Description
table_url
Required
str

The full URI to the table, including SAS token if used.

Keyword-Only Parameters

Name Description
credential

The credentials with which to authenticate. This is optional if the table URL already has a SAS token. The value can be one of AzureNamedKeyCredential (azure-core), AzureSasCredential (azure-core), or a TokenCredential implementation from azure-identity.

Returns

Type Description

A table client.

get_entity

Gets a single entity in a table.

async get_entity(partition_key: str, row_key: str, *, select: str | List[str] | None = None, **kwargs) -> TableEntity

Parameters

Name Description
partition_key
Required
str

The partition key of the entity.

row_key
Required
str

The row key of the entity.

Keyword-Only Parameters

Name Description
select
str or list[str] or None

Specify desired properties of an entity to return.

Returns

Type Description

Dictionary mapping operation metadata returned from the service.

Exceptions

Type Description

Examples

Getting an entity with PartitionKey and RowKey from a table


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

get_table_access_policy

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

async get_table_access_policy(**kwargs) -> Mapping[str, TableAccessPolicy | None]

Returns

Type Description

Dictionary of SignedIdentifiers.

Exceptions

Type Description

list_entities

Lists entities in a table.

list_entities(*, results_per_page: int | None = None, select: str | List[str] | None = None, **kwargs) -> AsyncItemPaged[TableEntity]

Keyword-Only Parameters

Name Description
results_per_page
int or None

Number of entities returned per service request.

select
str or list[str] or None

Specify desired properties of an entity to return.

Returns

Type Description

An async iterator of TableEntity

Exceptions

Type Description

Examples

Listing all entities held within a table


   # Query the entities in the table
   i = 0
   async for entity in table.list_entities():
       print(f"Entity #{entity}: {i}")
       i += 1

query_entities

Queries entities in a table.

query_entities(query_filter: str, *, results_per_page: int | None = None, select: str | List[str] | None = None, parameters: Dict[str, Any] | None = None, **kwargs) -> AsyncItemPaged[TableEntity]

Parameters

Name Description
query_filter
Required
str

Specify a filter to return certain entities. For more information on filter formatting, see the samples documentation.

Keyword-Only Parameters

Name Description
results_per_page
int or None

Number of entities returned per service request.

select
str or list[str] or None

Specify desired properties of an entity to return.

parameters
dict[str, Any] or None

Dictionary for formatting query with additional, user defined parameters

Returns

Type Description

An async iterator of TableEntity

Exceptions

Type Description

Examples

Querying entities held within a table


   async with TableClient.from_connection_string(self.connection_string, self.table_name) as table_client:
       try:
           print("Basic sample:")
           print("Entities with name: marker")
           parameters: Dict[str, Any] = {"name": "marker"}
           name_filter = "Name eq @name"
           queried_entities = table_client.query_entities(
               query_filter=name_filter, select=["Brand", "Color"], parameters=parameters
           )
           async for entity_chosen in queried_entities:
               print(entity_chosen)

           print("Sample for querying entities with multiple params:")
           print("Entities with name: marker and brand: Crayola")
           parameters = {"name": "marker", "brand": "Crayola"}
           name_filter = "Name eq @name and Brand eq @brand"
           queried_entities = table_client.query_entities(
               query_filter=name_filter, select=["Brand", "Color"], parameters=parameters
           )
           async for entity_chosen in queried_entities:
               print(entity_chosen)

           print("Sample for querying entities' values:")
           print("Entities with 25 < Value < 50")
           parameters = {"lower": 25, "upper": 50}
           name_filter = "Value gt @lower and Value lt @upper"
           queried_entities = table_client.query_entities(
               query_filter=name_filter, select=["Value"], parameters=parameters
           )
           async for entity_chosen in queried_entities:
               print(entity_chosen)
       except HttpResponseError as e:
           raise

set_table_access_policy

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

async set_table_access_policy(signed_identifiers: Mapping[str, TableAccessPolicy | None], **kwargs) -> None

Parameters

Name Description
signed_identifiers
Required

Access policies to set for the table.

Returns

Type Description

None

Exceptions

Type Description

submit_transaction

Commits a list of operations as a single transaction.

If any one of these operations fails, the entire transaction will be rejected.

async submit_transaction(operations: Iterable[Tuple[TransactionOperation | str, TableEntity | Mapping[str, Any]] | Tuple[TransactionOperation | str, TableEntity | Mapping[str, Any], Mapping[str, Any]]] | AsyncIterable[Tuple[TransactionOperation | str, TableEntity | Mapping[str, Any]] | Tuple[TransactionOperation | str, TableEntity | Mapping[str, Any], Mapping[str, Any]]], **kwargs) -> List[Mapping[str, Any]]

Parameters

Name Description
operations
Required
Union[Iterable[Tuple[str, <xref:Entity>, Mapping[str, Any]]],AsyncIterable[Tuple[str, <xref:Entity>, Mapping[str, Any]]]]

The list of operations to commit in a transaction. This should be an iterable (or async iterable) of tuples containing an operation name, the entity on which to operate, and optionally, a dict of additional kwargs for that operation. For example:


   - ('upsert', {'PartitionKey': 'A', 'RowKey': 'B'})
   - ('upsert', {'PartitionKey': 'A', 'RowKey': 'B'}, {'mode': UpdateMode.REPLACE})

Returns

Type Description

A list of mappings with response metadata for each operation in the transaction.

Exceptions

Type Description
:class:` azure.data.tables.TableTransactionError`

Examples

Using transactions to send multiple requests at once


   from azure.data.tables.aio import TableClient
   from azure.data.tables import TableTransactionError
   from azure.core.exceptions import ResourceExistsError

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

   # Instantiate a TableServiceClient using a connection string
   async with TableClient.from_connection_string(
       conn_str=self.connection_string, table_name=self.table_name
   ) as table_client:

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

       await table_client.upsert_entity(entity2)
       await table_client.upsert_entity(entity3)
       await table_client.upsert_entity(entity4)

       operations: List[TransactionOperationType] = [
           ("create", entity1),
           ("delete", entity2),
           ("upsert", entity3),
           ("update", entity4, {"mode": "replace"}),
       ]
       try:
           await table_client.submit_transaction(operations)
       except TableTransactionError as e:
           print("There was an error with the transaction operation")
           print(f"Error: {e}")

update_entity

Updates an entity in a table.

async update_entity(entity: TableEntity | Mapping[str, Any], mode: str | UpdateMode = UpdateMode.MERGE, *, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs) -> Mapping[str, Any]

Parameters

Name Description
entity
Required

The properties for the table entity.

mode
Required

Merge or Replace entity.

Keyword-Only Parameters

Name Description
etag
str or None

Etag of the entity.

match_condition

The condition under which to perform the operation. Supported values include: MatchConditions.IfNotModified, MatchConditions.Unconditionally.

Returns

Type Description

Dictionary of operation metadata returned from service.

Exceptions

Type Description

Examples

Updating an already existing entity in a Table


   # 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(f"Replaced entity: {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(f"Merged entity: {merged}")

upsert_entity

Updates (merge or replace) an entity into a table.

async upsert_entity(entity: TableEntity | Mapping[str, Any], mode: str | UpdateMode = UpdateMode.MERGE, **kwargs) -> Mapping[str, Any]

Parameters

Name Description
entity
Required

The properties for the table entity.

mode
Required

Merge or Replace entity.

Returns

Type Description

Dictionary mapping operation metadata returned from the service.

Exceptions

Type Description

Examples

Replacing/Merging or Inserting an entity into a table


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

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

Attributes

api_version

The version of the Storage API used for requests.

Returns

Type Description

The Storage API version.

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 <xref:azure.data.tables.aio.location_mode>.

Returns

Type Description
str

The full endpoint URL including SAS token if used.