TableClient Class
A client to interact with a specific Table in an Azure Tables account.
Create TableClient from a Credential.
- Inheritance
-
azure.data.tables._base_client.TablesBaseClientTableClient
Constructor
TableClient(endpoint: str, table_name: str, *, credential: AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs)
Parameters
- credential
- AzureNamedKeyCredential or AzureSasCredential or TokenCredential or None
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 TokenCredential implementation from azure-identity.
- api_version
- str
Specifies the version of the operation to use for this request. Default value is "2019-02-02".
Variables
- 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 storage endpoint.
- api_version
- str
The service API version.
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 |
Insert entity in a table. |
create_table |
Creates a new table under the current account. |
delete_entity |
Deletes the specified entity in a table. No error will be raised if the entity or PartitionKey-RowKey pairing is not found. |
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. AzureSasCredential (azure-core), or a TokenCredential implementation from azure-identity. :paramtype credential: ~azure.core.credentials.AzureNamedKeyCredential or ~azure.core.credentials.AzureSasCredential or None |
get_entity |
Get 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 |
Lists 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 |
Commit a list of operations as a single transaction. If any one of these operations fails, the entire transaction will be rejected. |
update_entity |
Update entity in a table. |
upsert_entity |
Update/Merge or Insert entity into table. |
close
This method is to close the sockets opened by the client. It need not be used when using with a context manager.
close() -> None
create_entity
Insert entity in a table.
create_entity(entity: TableEntity | Mapping[str, Any], **kwargs) -> Dict[str, Any]
Parameters
Returns
Dictionary mapping operation metadata returned from the service
Return type
Exceptions
Examples
Creating and adding an entity to a Table
try:
resp = table_client.create_entity(entity=self.entity)
print(resp)
except ResourceExistsError:
print("Entity already exists")
create_table
Creates a new table under the current account.
create_table(**kwargs) -> TableItem
Returns
A TableItem representing the created table.
Return type
Exceptions
If the entity already exists
Examples
Creating a table from the TableClient object
with TableClient.from_connection_string(
conn_str=self.connection_string, table_name=self.table_name
) as table_client:
try:
table_item = table_client.create_table()
print("Created table {}!".format(table_item.name))
except ResourceExistsError:
print("Table already exists")
delete_entity
Deletes the specified entity in a table. No error will be raised if the entity or PartitionKey-RowKey pairing is not found.
delete_entity(partition_key: str, row_key: str, **kwargs) -> None
Parameters
- etag
- str
Etag of the entity
- match_condition
- MatchConditions
The condition under which to perform the operation. Supported values include: MatchConditions.IfNotModified, MatchConditions.Unconditionally. The default value is Unconditionally.
Returns
None
Exceptions
Examples
Deleting an entity of a Table
table_client.delete_entity(row_key=self.entity["RowKey"], partition_key=self.entity["PartitionKey"])
print("Successfully deleted!")
delete_table
Deletes the table under the current account. No error will be raised if the table does not exist
delete_table(**kwargs) -> None
Returns
None
Exceptions
Examples
Deleting a table from the TableClient object
with TableClient.from_connection_string(
conn_str=self.connection_string, table_name=self.table_name
) as table_client:
table_client.delete_table()
print("Deleted table {}!".format(table_client.table_name))
from_connection_string
Create TableClient from a Connection String.
from_connection_string(conn_str: str, table_name: str, **kwargs) -> TableClient
Parameters
Returns
A table client.
Return type
Examples
Authenticating a TableServiceClient from a connection_string
from azure.data.tables import TableClient
with TableClient.from_connection_string(
conn_str=self.connection_string, table_name="tableName"
) as table_client:
print("Table name: {}".format(table_client.table_name))
from_table_url
A client to interact with a specific Table.
AzureSasCredential (azure-core), or a TokenCredential implementation from azure-identity. :paramtype credential:
~azure.core.credentials.AzureNamedKeyCredential or ~azure.core.credentials.AzureSasCredential or None
from_table_url(table_url: str, *, credential: AzureNamedKeyCredential | AzureSasCredential | None = None, **kwargs) -> TableClient
Parameters
- table_url
Returns
A table client.
Return type
get_entity
Get a single entity in a table.
get_entity(partition_key: str, row_key: str, **kwargs) -> TableEntity
Parameters
Returns
Dictionary mapping operation metadata returned from the service
Return type
Exceptions
Examples
Get a single entity from a table
# Get Entity by partition and row key
got_entity = table.get_entity(partition_key=my_entity["PartitionKey"], row_key=my_entity["RowKey"])
print("Received entity: {}".format(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.
get_table_access_policy(**kwargs) -> Dict[str, TableAccessPolicy | None]
Returns
Dictionary of SignedIdentifiers
Return type
Exceptions
list_entities
Lists entities in a table.
list_entities(**kwargs) -> ItemPaged[TableEntity]
Parameters
- results_per_page
- int
Number of entities returned per service request.
Returns
An iterator of TableEntity
Return type
Exceptions
Examples
List all entities held within a table
# Query the entities in the table
entities = list(table.list_entities())
for i, entity in enumerate(entities):
print("Entity #{}: {}".format(entity, i))
query_entities
Lists entities in a table.
query_entities(query_filter: str, **kwargs) -> ItemPaged[TableEntity]
Parameters
- query_filter
- str
Specify a filter to return certain entities. For more information on filter formatting, see the samples documentation.
- results_per_page
- int
Number of entities returned per service request.
Returns
An iterator of TableEntity
Return type
Exceptions
Examples
Query entities held within a table
with TableClient.from_connection_string(self.connection_string, self.table_name) as table_client:
try:
print("Basic sample:")
print("Entities with name: marker")
parameters = {"name": "marker"}
name_filter = "Name eq @name"
queried_entities = table_client.query_entities(
query_filter=name_filter, select=["Brand", "Color"], parameters=parameters
)
for entity_chosen in queried_entities:
print(entity_chosen)
print("Sample for querying entities withtout metadata:")
print("Entities with name: marker")
parameters = {"name": "marker"}
name_filter = "Name eq @name"
headers = {"Accept": "application/json;odata=nometadata"}
queried_entities = table_client.query_entities(
query_filter=name_filter, select=["Brand", "Color"], parameters=parameters, headers=headers
)
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
)
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} # type: ignore
name_filter = "Value gt @lower and Value lt @upper"
queried_entities = table_client.query_entities(
query_filter=name_filter, select=["Value"], parameters=parameters
)
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.
set_table_access_policy(signed_identifiers: Dict[str, TableAccessPolicy | None], **kwargs) -> None
Parameters
Access policies to set for the table
Returns
None
Exceptions
submit_transaction
Commit a list of operations as a single transaction.
If any one of these operations fails, the entire transaction will be rejected.
submit_transaction(operations: Iterable[Tuple[TransactionOperation | str, TableEntity | Mapping[str, Any]] | Tuple[TransactionOperation | str, TableEntity | Mapping[str, Any], Mapping[str, Any]]], **kwargs) -> List[Mapping[str, Any]]
Parameters
The list of operations to commit in a transaction. This should be an 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
A list of mappings with response metadata for each operation in the transaction.
Return type
Exceptions
Examples
Using transactions to send multiple requests at once
from azure.data.tables import TableClient, 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:
self.table_client.create_table()
print("Created table")
except ResourceExistsError:
print("Table already exists")
self.table_client.upsert_entity(entity2)
self.table_client.upsert_entity(entity3)
self.table_client.upsert_entity(entity4)
operations = [
("upsert", entity1),
("delete", entity2),
("upsert", entity3),
("update", entity4, {"mode": "replace"}),
]
try:
self.table_client.submit_transaction(operations) # type: ignore[arg-type]
except TableTransactionError as e:
print("There was an error with the transaction operation")
print(e)
update_entity
Update entity in a table.
update_entity(entity: TableEntity | Mapping[str, Any], mode: UpdateMode = UpdateMode.MERGE, **kwargs) -> Dict[str, Any]
Parameters
- etag
- str
Etag of the entity
- match_condition
- MatchConditions
The condition under which to perform the operation. Supported values include: MatchConditions.IfNotModified, MatchConditions.Unconditionally. The default value is Unconditionally.
Returns
Dictionary mapping operation metadata returned from the service
Return type
Exceptions
Examples
Updating an already exiting entity in a Table
# Update the entity
created["text"] = "NewMarker"
table.update_entity(mode=UpdateMode.REPLACE, entity=created)
# Get the replaced entity
replaced = table.get_entity(partition_key=created["PartitionKey"], row_key=created["RowKey"])
print("Replaced entity: {}".format(replaced))
# Merge the entity
replaced["color"] = "Blue"
table.update_entity(mode=UpdateMode.MERGE, entity=replaced)
# Get the merged entity
merged = table.get_entity(partition_key=replaced["PartitionKey"], row_key=replaced["RowKey"])
print("Merged entity: {}".format(merged))
upsert_entity
Update/Merge or Insert entity into table.
upsert_entity(entity: TableEntity | Mapping[str, Any], mode: UpdateMode = UpdateMode.MERGE, **kwargs) -> Dict[str, Any]
Parameters
Returns
Dictionary mapping operation metadata returned from the service
Return type
Exceptions
Examples
Update/merge or insert an entity into a table
# Try Replace and insert on fail
insert_entity = table.upsert_entity(mode=UpdateMode.REPLACE, entity=entity1)
print("Inserted entity: {}".format(insert_entity))
created["text"] = "NewMarker"
merged_entity = table.upsert_entity(mode=UpdateMode.MERGE, entity=entity)
print("Merged entity: {}".format(merged_entity))
Attributes
api_version
The version of the Storage API used for requests.
Returns
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.location_mode>.
Returns
The full endpoint URL including SAS token if used.
Return type
Feedback
Submit and view feedback for