From 4c15e4ee49d883c0b96d600ce6b0efed24a5da6f Mon Sep 17 00:00:00 2001 From: seankane-msft Date: Wed, 19 Aug 2020 11:55:26 -0700 Subject: [PATCH 1/3] updated each sample to use env variables, more informative print statements --- .../samples/create_query_entities.py | 30 ++++++----- .../samples/creation_deletion_of_table.py | 28 ++++++---- .../samples/inserting_deleting_entities.py | 51 ++++++++++--------- .../samples/querying_table.py | 34 ++++++++----- .../samples/table_exists_error_handling.py | 13 ++--- .../samples/table_samples_authentication.py | 25 ++++----- .../samples/table_samples_client.py | 42 +++++++-------- .../samples/table_samples_service.py | 35 ++++++------- .../samples/update_entity.py | 7 +++ 9 files changed, 146 insertions(+), 119 deletions(-) diff --git a/sdk/tables/azure-data-tables/samples/create_query_entities.py b/sdk/tables/azure-data-tables/samples/create_query_entities.py index 7277f7c9e067..108f4e326b4d 100644 --- a/sdk/tables/azure-data-tables/samples/create_query_entities.py +++ b/sdk/tables/azure-data-tables/samples/create_query_entities.py @@ -1,30 +1,32 @@ +import os + class CreateODataQuery(object): - connection_string = "DefaultEndpointsProtocol=https;AccountName=example;AccountKey" \ - "=fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==;EndpointSuffix=core.windows.net " - account_url = "https://example.table.core.windows.net/" - account_name = "example" - access_key = "fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==" - - partition_key = "color" - row_key = "brand" - # Creating query filter for that table - table_name = "Office Supplies" + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" + entity_name = "marker" + name_filter = "EntityName eq '{}'".format(entity_name) + @classmethod def sample_query_entities(self): from azure.data.tables import TableClient from azure.core.exceptions import HttpResponseError - table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) + table_client = TableClient.from_connection_string(self.connection_string, self.table_name) + try: queried_entities = table_client.query_entities(filter=self.name_filter, select="brand,color") - # queried_entities type is ItemPaged for entity_chosen in queried_entities: - # create a list of the entities and iterate through them to print each one out - # calls to the service to get more entities are made without user knowledge print(entity_chosen) + except HttpResponseError as e: print(e.message) + +if __name__ == '__main__': + CreateODataQuery.sample_query_entities() \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py b/sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py index e9a614968af4..ebc98eebf0bf 100644 --- a/sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py +++ b/sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py @@ -1,20 +1,28 @@ +import os +import logging + +_LOGGER = logging.getLogger(__name__) + class CreateDeleteTable(object): - connection_string = "DefaultEndpointsProtocol=https;AccountName=example;AccountKey=fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==;EndpointSuffix=core.windows.net" + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") table_name = "OfficeSupplies" - account_url = "https://example.table.core.windows.net/" - account_name = "example" - access_key = "fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==" + def shared_key_credential(self): from azure.data.tables import TableServiceClient table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) + def connection_string_auth(self): from azure.data.tables import TableServiceClient table_service_client = TableServiceClient.from_connection_string(conn_str=self.connection_string) + def sas_token_auth(self): from azure.data.tables import TableServiceClient from azure.data.tables._shared.table_shared_access_signature import generate_account_sas @@ -31,28 +39,30 @@ def sas_token_auth(self): expiry=datetime.utcnow() + timedelta(hours=1), start=datetime.utcnow() - timedelta(minutes=1), ) - table_service_client = TableServiceClient(account_url=self.account_url,credential=token) + table_service_client = TableServiceClient(account_url=self.account_url, credential=token) + def create_table(self): from azure.data.tables import TableServiceClient from azure.core.exceptions import ResourceExistsError - table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) + table_service_client = TableServiceClient.from_connection_string(self.connection_string) try: table_created = table_service_client.create_table(table_name=self.table_name) print(table_created.table_name) except ResourceExistsError: - print("TableExists") + print("Table already exists") + def delete_table(self): from azure.data.tables import TableServiceClient from azure.core.exceptions import ResourceNotFoundError - table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) + table_service_client = TableServiceClient.from_connection_string(self.connection_string) try: table_service_client.delete_table(table_name=self.table_name) except ResourceNotFoundError: - print("TableNotFound") + print("Table coult not be found") if __name__ == '__main__': diff --git a/sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py b/sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py index 10c6a35f1453..246b03099ca5 100644 --- a/sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py +++ b/sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py @@ -1,9 +1,11 @@ +import os + class InsertDeleteEntity(object): - connection_string = "DefaultEndpointsProtocol=https;AccountName=example;AccountKey=fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==;EndpointSuffix=core.windows.net" - table_name = "NAME" - account_url = "https://example.table.core.windows.net/" - account_name = "example" - access_key = "fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==" + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" # Assuming there is a created table entity = { @@ -19,40 +21,41 @@ def create_entity(self): from azure.data.tables import TableClient from azure.core.exceptions import ResourceExistsError - table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) + # table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) + table_client = TableClient.from_connection_string(self.connection_string, self.table_name) + try: inserted_entity = table_client.create_entity(entity=self.entity) - # inserted_entity type is dict[str,object] + print(inserted_entity.items()) # print out key-value pair of entity except ResourceExistsError: - print("EntityExists") + print("Entity already exists") def delete_entity(self): from azure.data.tables import TableClient - from azure.core.exceptions import ResourceNotFoundError + from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError from azure.core import MatchConditions - table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) + # table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) + table_client = TableClient.from_connection_string(self.connection_string, self.table_name) # Create entity to delete (to showcase etag) - entity_created = table_client.create_entity(entity=self.entity) - - # show without calling metadata, cannot access etag try: - entity_created.etag - except AttributeError: - print("Need to get metadata of entity") - - # In order to access etag as a part of the entity, need to call metadata on the entity - metadata = entity_created.metadata() - - # Can now get etag - etag = metadata['etag'] + entity_created = table_client.create_entity(entity=self.entity) + except ResourceExistsError as e: + print("Entity already exists!") try: # will delete if match_condition and etag are satisfied - table_client.delete_entity(entity=self.entity, etag=etag, match_condition=MatchConditions.IfNotModified) + table_client.delete_entity(row_key=self.entity["RowKey"], partition_key=self.entity["PartitionKey"]) + print("Successfully deleted!") except ResourceNotFoundError: - print("EntityDoesNotExists") + print("Entity does not exists") + + +if __name__ == '__main__': + ide = InsertDeleteEntity() + ide.create_entity() + ide.delete_entity() \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/querying_table.py b/sdk/tables/azure-data-tables/samples/querying_table.py index 2dd69452b6ec..21b90a00e7a9 100644 --- a/sdk/tables/azure-data-tables/samples/querying_table.py +++ b/sdk/tables/azure-data-tables/samples/querying_table.py @@ -1,25 +1,35 @@ +import os + class QueryTable(object): - connection_string = "DefaultEndpointsProtocol=https;AccountName=example;AccountKey=fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==;EndpointSuffix=core.windows.net" - table_name = "NAME" - account_url = "https://example.table.core.windows.net/" - account_name = "example" - access_key = "fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==" + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" # Creating query filter for that table - table_name = "Office Supplies" name_filter = "TableName eq '{}'".format(table_name) + @classmethod def query_tables(self): from azure.data.tables import TableServiceClient + from azure.core.exceptions import ResourceExistsError + + # table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) + table_service_client = TableServiceClient.from_connection_string(self.connection_string) - table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) # Create Tables to query - my_table = table_service_client.create_table(table_name=self.table_name) - print(my_table) + try: + my_table = table_service_client.create_table(table_name=self.table_name) + print(my_table.table_name) + except ResourceExistsError: + print("Table already exists!") + # Query tables queried_tables = table_service_client.query_tables(filter=self.name_filter, results_per_page=10) - # table_client.query_tables() returns an itemPaged - # queried_tables is a list of filtered tables for table in queried_tables: - print(table) + print(table.table_name) + +if __name__ == "__main__": + QueryTable.query_tables() \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/table_exists_error_handling.py b/sdk/tables/azure-data-tables/samples/table_exists_error_handling.py index bad368724447..15bfcd13e9b9 100644 --- a/sdk/tables/azure-data-tables/samples/table_exists_error_handling.py +++ b/sdk/tables/azure-data-tables/samples/table_exists_error_handling.py @@ -1,22 +1,23 @@ +import os + class TableErrorHandling: - connection_string = "DefaultEndpointsProtocol=https;AccountName=example;AccountKey=fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==;EndpointSuffix=core.windows.net" + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") table_name = "OfficeSupplies" - account_url = "https://example.table.core.windows.net/" - account_name = "example" - access_key = "fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==" def create_table_if_exists(self): from azure.data.tables import TableServiceClient from azure.core.exceptions import ResourceExistsError - # create table table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) table_service_client.create_table(table_name=self.table_name) try: # try to create existing table, ResourceExistsError will be thrown table_service_client.create_table(table_name=self.table_name) except ResourceExistsError: - print("TableExists") + print("Table already exists") if __name__ == '__main__': diff --git a/sdk/tables/azure-data-tables/samples/table_samples_authentication.py b/sdk/tables/azure-data-tables/samples/table_samples_authentication.py index 8896918b1f59..09d77a3a67ec 100644 --- a/sdk/tables/azure-data-tables/samples/table_samples_authentication.py +++ b/sdk/tables/azure-data-tables/samples/table_samples_authentication.py @@ -32,32 +32,26 @@ class TableAuthSamples(object): - - connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") - - account_url = os.getenv("AZURE_STORAGE_ACCOUNT_URL") - account_name = os.getenv("AZURE_STORAGE_ACCOUNT_NAME") - access_key = os.getenv("AZURE_STORAGE_ACCESS_KEY") + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") def authentication_by_connection_string(self): # Instantiate a TableServiceClient using a connection string # [START auth_from_connection_string] from azure.data.tables import TableServiceClient table_service = TableServiceClient.from_connection_string(conn_str=self.connection_string) - # [END auth_from_connection_string] - - # Get information for the Table Service properties = table_service.get_service_properties() + print("Connection String: {}".format(properties)) def authentication_by_shared_key(self): # Instantiate a TableServiceClient using a shared access key # [START create_Table_service_client] from azure.data.tables import TableServiceClient table_service = TableServiceClient(account_url=self.account_url, credential=self.access_key) - # [END create_table_service_client] - - # Get information for the Table Service properties = table_service.get_service_properties() + print("Shared Key: {}".format(properties)) def authentication_by_shared_access_signature(self): # Instantiate a TableServiceClient using a connection string @@ -66,7 +60,7 @@ def authentication_by_shared_access_signature(self): # Create a SAS token to use for authentication of a client from azure.data.tables import generate_account_sas, ResourceTypes, AccountSasPermissions - + print(self.account_name) sas_token = generate_account_sas( self.account_name, self.access_key, @@ -77,9 +71,8 @@ def authentication_by_shared_access_signature(self): token_auth_table_service = TableServiceClient(account_url=self.account_url, credential=sas_token) - # Get information for the Table Service - properties = token_auth_table_service.get_service_properties() - + properties = table_service.get_service_properties() + print("Shared Access Signature: {}".format(properties)) if __name__ == '__main__': sample = TableAuthSamples() diff --git a/sdk/tables/azure-data-tables/samples/table_samples_client.py b/sdk/tables/azure-data-tables/samples/table_samples_client.py index cb32c94196d0..297a189bfb7b 100644 --- a/sdk/tables/azure-data-tables/samples/table_samples_client.py +++ b/sdk/tables/azure-data-tables/samples/table_samples_client.py @@ -27,7 +27,7 @@ class TableEntitySamples(object): - connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") def set_access_policy(self): # [START create_table_client_from_connection_string] @@ -92,22 +92,22 @@ def create_and_get_entities(self): } try: # [START create_entity] - created_entity = table.create_entity(table_entity_properties=my_entity) - print(created_entity) + created_entity = table.create_entity(entity=my_entity) + print("Created entity: {}".format(created_entity)) # [END create_entity] # [START get_entity] # Get Entity by partition and row key got_entity = table.get_entity(partition_key=my_entity['PartitionKey'], row_key=my_entity['RowKey']) - print(got_entity) + print("Received entity: {}".format(got_entity)) # [END get_entity] finally: # Delete the table table.delete_table() - def query_entities(self): + def list_all_entities(self): # Instantiate a table service client from azure.data.tables import TableClient table = TableClient.from_connection_string(self.connection_string, table_name="mytable4") @@ -120,14 +120,14 @@ def query_entities(self): try: # Create entities - table.create_entity(table_entity_properties=entity) - table.create_entity(table_entity_properties=entity1) + table.create_entity(entity=entity) + table.create_entity(entity=entity1) # [START query_entities] # Query the entities in the table - entities = list(table.query_entities()) + entities = list(table.list_entities()) - for e in entities: - print(e) + for entity, i in enumerate(entities): + print("Entity #{}: {}".format(entity, i)) # [END query_entities] finally: @@ -147,17 +147,17 @@ def upsert_entities(self): try: # Create entities - created = table.create_entity(table_entity_properties=entity) + created = table.create_entity(entity=entity) # [START upsert_entity] # Try Replace and then Insert on Fail - insert_entity = table.upsert_entity(mode=UpdateMode.replace, table_entity_properties=entity1) - print(insert_entity) + insert_entity = 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 = table.upsert_entity(mode=UpdateMode.MERGE, table_entity_properties=entity) - print(merged_entity) + merged_entity = table.upsert_entity(mode=UpdateMode.MERGE, entity=entity) + print("Merged entity: {}".format(merged_entity)) # [END upsert_entity] finally: @@ -176,26 +176,26 @@ def update_entities(self): try: # Create entity - created = table.create_entity(table_entity_properties=entity) + created = table.create_entity(entity=entity) # [START update_entity] # Update the entity created.text = "NewMarker" - table.update_entity(mode=UpdateMode.replace, table_entity_properties=created) + 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) + print("Replaced entity: {}".format(replaced)) # Merge the entity replaced.color = "Blue" - table.update_entity(mode=UpdateMode.MERGE, table_entity_properties=replaced) + 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) + print("Merged entity: {}".format(merged)) # [END update_entity] finally: @@ -207,6 +207,6 @@ def update_entities(self): sample = TableEntitySamples() sample.set_access_policy() sample.create_and_get_entities() - sample.query_entities() + sample.list_all_entities() sample.upsert_entities() sample.update_entities() diff --git a/sdk/tables/azure-data-tables/samples/table_samples_service.py b/sdk/tables/azure-data-tables/samples/table_samples_service.py index eaf2bae86d9d..fc6da15dd235 100644 --- a/sdk/tables/azure-data-tables/samples/table_samples_service.py +++ b/sdk/tables/azure-data-tables/samples/table_samples_service.py @@ -24,7 +24,7 @@ class TableServiceSamples(object): - connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") def table_service_properties(self): # Instantiate the TableServiceClient from a connection string @@ -76,39 +76,40 @@ def tables_in_account(self): # [START tsc_create_table] table_service.create_table("mytable1") + table_service.create_table("mytable2") + table_service.create_table("mytable3") # [END tsc_create_table] try: # [START tsc_list_tables] # List all the tables in the service - list_tables = table_service.query_tables() + list_tables = table_service.list_tables() for table in list_tables: - print(table) + print(table.table_name) # List the tables in the service that start with the name "my" - list_my_tables = table_service.query_tables(select="my") + list_my_tables = table_service.query_tables(filter="my") for table in list_my_tables: - print(table) + print(table.table_name) # [END tsc_list_tables] finally: # [START tsc_delete_table] - table_service.delete_table(table_name="mytable1") + self.delete_tables() # [END tsc_delete_table] - def get_table_client(self): - # Instantiate the TableServiceClient from a connection string - from azure.data.tables import TableServiceClient, TableClient - table_service = TableServiceClient.from_connection_string(conn_str=self.connection_string) - - # [START get_table_client] - # Get the table client to interact with a specific table - table = table_service.get_table_client(table="mytable2") - # [END get_table_client] - + def delete_tables(self): + from azure.data.tables import TableServiceClient + ts = TableServiceClient.from_connection_string(conn_str=self.connection_string) + try: + ts.delete_table(table_name="mytable1") + ts.delete_table(table_name="mytable2") + ts.delete_table(table_name="mytable3") + except: + pass if __name__ == '__main__': sample = TableServiceSamples() + sample.delete_tables() sample.table_service_properties() sample.tables_in_account() - sample.get_table_client() diff --git a/sdk/tables/azure-data-tables/samples/update_entity.py b/sdk/tables/azure-data-tables/samples/update_entity.py index 75af124aab9b..362ba3db8878 100644 --- a/sdk/tables/azure-data-tables/samples/update_entity.py +++ b/sdk/tables/azure-data-tables/samples/update_entity.py @@ -1,3 +1,5 @@ +import os + class UpdateEntity(object): connection_string = "DefaultEndpointsProtocol=https;AccountName=example;AccountKey" \ "=fasgfbhBDFAShjDQ4jkvbnaBFHJOWS6gkjngdakeKFNLK==;EndpointSuffix=core.windows.net " @@ -34,3 +36,8 @@ def upsert_entity(self): table_client.upsert_entity(entity=self.entity, mode=UpdateMode.REPLACE) # no error will be thrown - it will insert + +if __name__ == "__main__": + u = UpdateEntity() + u.update_entity() + u.upsert_entity() \ No newline at end of file From 75c79823e23bb9a385f1ad438a6317a000faa4d5 Mon Sep 17 00:00:00 2001 From: seankane-msft Date: Mon, 24 Aug 2020 10:46:27 -0700 Subject: [PATCH 2/3] added a readme, and async versions for auth and create/delete operations --- .../azure-data-tables/samples/README.md | 58 +++++++++++++ ...entication.py => sample_authentication.py} | 0 .../samples/sample_authentication_async.py | 85 +++++++++++++++++++ ...table.py => sample_create_delete_table.py} | 38 +-------- .../sample_create_delete_table_async.py | 46 ++++++++++ 5 files changed, 192 insertions(+), 35 deletions(-) create mode 100644 sdk/tables/azure-data-tables/samples/README.md rename sdk/tables/azure-data-tables/samples/{table_samples_authentication.py => sample_authentication.py} (100%) create mode 100644 sdk/tables/azure-data-tables/samples/sample_authentication_async.py rename sdk/tables/azure-data-tables/samples/{creation_deletion_of_table.py => sample_create_delete_table.py} (50%) create mode 100644 sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py diff --git a/sdk/tables/azure-data-tables/samples/README.md b/sdk/tables/azure-data-tables/samples/README.md new file mode 100644 index 000000000000..46d7df2a6c1b --- /dev/null +++ b/sdk/tables/azure-data-tables/samples/README.md @@ -0,0 +1,58 @@ +--- +page_type: sample +languages: + - python +products: + - azure + - azure-data-tables +urlFragment: tables-samples +--- + +# Samples for Azure Tables client library for Python + +These code samples show common scenario operations with the Azure Text Analytics client library. +The async versions of the samples require Python 3.5 or later. + +You can authenticate your client with a Tables API key: +* See [sample_authentication.py][sample_authentication] and [sample_authentication_async.py][sample_authentication_async] for how to authenticate in the above cases. + +These sample programs show common scenarios for the Text Analytics client's offerings. + +|**File Name**|**Description**| +|-------------|---------------| +|[sample_create_client.py][create_client] and [sample_create_client_async.py][create_client_async]|Instantiate a table client|Authorizing a `TableServiceClient` object| +|[sample_create_delete_table.py][create_delete_table] and [sample_create_delete_table_async.py][create_delete_table_async]|Creating a table in a storage account| + + + + +[sample_authentication]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/samples_authentication.py +[sample_authentication_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/samples_authentication_async.py + +[create_delete_table]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_create_delete_table.py +[create_delete_table_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py + + +[detect_language]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_detect_language.py +[detect_language_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py +[recognize_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_entities.py +[recognize_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py +[recognize_linked_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_linked_entities.py +[recognize_linked_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py +[recognize_pii_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_pii_entities.py +[recognize_pii_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py +[extract_key_phrases]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_key_phrases.py +[extract_key_phrases_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py +[analyze_sentiment]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment.py +[analyze_sentiment_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py +[get_detailed_diagnostics_information]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_get_detailed_diagnostics_information.py +[get_detailed_diagnostics_information_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_get_detailed_diagnostics_information_async.py +[sample_alternative_document_input]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_alternative_document_input.py +[sample_alternative_document_input_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_alternative_document_input_async.py +[sample_analyze_sentiment_with_opinion_mining]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment_with_opinion_mining.py +[sample_analyze_sentiment_with_opinion_mining_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_with_opinion_mining_async.py +[pip]: https://pypi.org/project/pip/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_text_analytics_account]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=singleservice%2Cwindows +[azure_identity_pip]: https://pypi.org/project/azure-identity/ +[api_reference_documentation]: https://aka.ms/azsdk-python-textanalytics-ref-docs \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/table_samples_authentication.py b/sdk/tables/azure-data-tables/samples/sample_authentication.py similarity index 100% rename from sdk/tables/azure-data-tables/samples/table_samples_authentication.py rename to sdk/tables/azure-data-tables/samples/sample_authentication.py diff --git a/sdk/tables/azure-data-tables/samples/sample_authentication_async.py b/sdk/tables/azure-data-tables/samples/sample_authentication_async.py new file mode 100644 index 000000000000..d65248f4e581 --- /dev/null +++ b/sdk/tables/azure-data-tables/samples/sample_authentication_async.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: table_samples_authentication.py + +DESCRIPTION: + These samples demonstrate authenticating a client via: + * connection string + * shared access key + * generating a sas token with which the returned signature can be used with + the credential parameter of any TableServiceClient or TableClient + +USAGE: + python table_samples_authentication.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account + 2) AZURE_STORAGE_ACCOUNT_URL - the Table service account URL + 3) AZURE_STORAGE_ACCOUNT_NAME - the name of the storage account + 4) AZURE_STORAGE_ACCESS_KEY - the storage account access key +""" + + +from datetime import datetime, timedelta +import os +import asyncio + +class TableAuthSamples(object): + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + + async def authentication_by_connection_string(self): + # Instantiate a TableServiceClient using a connection string + # [START auth_from_connection_string] + from azure.data.tables.aio import TableServiceClient + table_service = TableServiceClient.from_connection_string(conn_str=self.connection_string) + properties = table_service.get_service_properties() + print("Connection String: {}".format(properties)) + + async def authentication_by_shared_key(self): + # Instantiate a TableServiceClient using a shared access key + # [START create_Table_service_client] + from azure.data.tables.aio import TableServiceClient + table_service = TableServiceClient(account_url=self.account_url, credential=self.access_key) + properties = table_service.get_service_properties() + print("Shared Key: {}".format(properties)) + + async def authentication_by_shared_access_signature(self): + # Instantiate a TableServiceClient using a connection string + from azure.data.tables.aio import TableServiceClient + table_service = TableServiceClient.from_connection_string(conn_str=self.connection_string) + + # 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) + ) + + token_auth_table_service = TableServiceClient(account_url=self.account_url, credential=sas_token) + + properties = await table_service.get_service_properties() + print("Shared Access Signature: {}".format(properties)) + +async def main(): + sample = TableAuthSamples() + await sample.authentication_by_connection_string() + await sample.authentication_by_shared_key() + await sample.authentication_by_shared_access_signature() + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py b/sdk/tables/azure-data-tables/samples/sample_create_delete_table.py similarity index 50% rename from sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py rename to sdk/tables/azure-data-tables/samples/sample_create_delete_table.py index 4851a667e3d6..f7a4a1c16632 100644 --- a/sdk/tables/azure-data-tables/samples/creation_deletion_of_table.py +++ b/sdk/tables/azure-data-tables/samples/sample_create_delete_table.py @@ -11,39 +11,6 @@ class CreateDeleteTable(object): table_name = "OfficeSupplies" - def shared_key_credential(self): - from azure.data.tables import TableServiceClient - - table_service_client = TableServiceClient(account_url=self.account_url, credential=self.access_key) - - - def connection_string_auth(self): - from azure.data.tables import TableServiceClient - - table_service_client = TableServiceClient.from_connection_string(conn_str=self.connection_string) - - - def sas_token_auth(self): - from azure.data.tables import ( - TableServiceClient, - ResourceTypes, - AccountSasPermissions, - generate_account_sas - ) - import datetime - import timedelta - - token = generate_account_sas( - account_name=self.account_name, - account_key=self.account_key, - resource_types=ResourceTypes(object=True), - permission=AccountSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1), - start=datetime.utcnow() - timedelta(minutes=1), - ) - table_service_client = TableServiceClient(account_url=self.account_url, credential=token) - - def create_table(self): from azure.data.tables import TableServiceClient from azure.core.exceptions import ResourceExistsError @@ -51,7 +18,7 @@ def create_table(self): table_service_client = TableServiceClient.from_connection_string(self.connection_string) try: table_created = table_service_client.create_table(table_name=self.table_name) - print(table_created.table_name) + print("Created table {}!".format(table_created.table_name)) except ResourceExistsError: print("Table already exists") @@ -63,8 +30,9 @@ def delete_table(self): table_service_client = TableServiceClient.from_connection_string(self.connection_string) try: table_service_client.delete_table(table_name=self.table_name) + print("Deleted table {}!".format(self.table_name)) except ResourceNotFoundError: - print("Table coult not be found") + print("Table could not be found") if __name__ == '__main__': diff --git a/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py b/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py new file mode 100644 index 000000000000..ae8770d15e3c --- /dev/null +++ b/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py @@ -0,0 +1,46 @@ +import os +import logging +import asyncio + +_LOGGER = logging.getLogger(__name__) + +class CreateDeleteTable(object): + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" + + + async def create_table(self): + from azure.data.tables.aio import TableServiceClient + from azure.core.exceptions import ResourceExistsError + + table_service_client = TableServiceClient.from_connection_string(self.connection_string) + try: + table_created = await table_service_client.create_table(table_name=self.table_name) + print("Created table {}!".format(table_created.table_name)) + except ResourceExistsError: + print("Table already exists") + + + async def delete_table(self): + from azure.data.tables.aio import TableServiceClient + from azure.core.exceptions import ResourceNotFoundError + + table_service_client = TableServiceClient.from_connection_string(self.connection_string) + 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") + + +async def main(): + sample = CreateDeleteTable() + await sample.create_table() + await sample.delete_table() + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) \ No newline at end of file From 7a628ea7df6caa9ad6c5497b8586bbc059919e77 Mon Sep 17 00:00:00 2001 From: seankane-msft Date: Mon, 24 Aug 2020 12:57:30 -0700 Subject: [PATCH 3/3] added more files (copies for async), and a README to the samples portion --- .../azure-data-tables/samples/README.md | 59 ++++++++++------ .../samples/create_query_entities.py | 32 --------- .../sample_create_delete_table_async.py | 1 + ...es.py => sample_insert_delete_entities.py} | 22 +++--- .../sample_insert_delete_entities_async.py | 67 ++++++++++++++++++ .../samples/sample_query_table.py | 59 ++++++++++++++++ .../samples/sample_query_table_async.py | 70 +++++++++++++++++++ 7 files changed, 244 insertions(+), 66 deletions(-) delete mode 100644 sdk/tables/azure-data-tables/samples/create_query_entities.py rename sdk/tables/azure-data-tables/samples/{inserting_deleting_entities.py => sample_insert_delete_entities.py} (69%) create mode 100644 sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py create mode 100644 sdk/tables/azure-data-tables/samples/sample_query_table.py create mode 100644 sdk/tables/azure-data-tables/samples/sample_query_table_async.py diff --git a/sdk/tables/azure-data-tables/samples/README.md b/sdk/tables/azure-data-tables/samples/README.md index 46d7df2a6c1b..7c42a715bfc1 100644 --- a/sdk/tables/azure-data-tables/samples/README.md +++ b/sdk/tables/azure-data-tables/samples/README.md @@ -22,37 +22,50 @@ These sample programs show common scenarios for the Text Analytics client's offe |-------------|---------------| |[sample_create_client.py][create_client] and [sample_create_client_async.py][create_client_async]|Instantiate a table client|Authorizing a `TableServiceClient` object| |[sample_create_delete_table.py][create_delete_table] and [sample_create_delete_table_async.py][create_delete_table_async]|Creating a table in a storage account| +|[sample_insert_delete_entities.py][insert_delete_entities] and [sample_insert_delete_entities_async.py][insert_delete_entities_async]|Inserting and deleting individual entities into a table| +|[sample_query_table.py][query_table] and [sample_query_table_async.py][query_table_async]|Querying entities in a table| +### Prerequisites +* Python 2.7, or 3.5 or later is required to use this package. +* You must have an [Azure subscription](https://azure.microsoft.com/free/) and an +[Azure storage account](https://docs.microsoft.com/azure/storage/common/storage-account-overview) to use this package + or you must have a [Azure Cosmos Account](https://docs.microsoft.com/azure/cosmos-db/account-overview). + +## Setup + +1. Install the Azure Data Tables client library for Python with [pip](https://pypi.org/project/pip/): + +```bash +pip install --pre azure-data-tables +``` + + +2. Clone or download this sample repository +3. Open the sample folder in Visual Studio Code or your IDE of choice. + +## Running the samples + +1. Open a terminal window and `cd` to the directory that the samples are saved in. +2. Set the environment variables specified in the sample file you wish to run. +3. Follow the usage described in the file, e.g. `python sample_detect_language.py` + +## Next steps + +Check out the [API reference documentation][api_reference_documentation] to learn more about +what you can do with the Azure Text Analytics client library. +[api_reference_documentation]: https://aka.ms/azsdk/python/tables/docs + [sample_authentication]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/samples_authentication.py [sample_authentication_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/samples_authentication_async.py [create_delete_table]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_create_delete_table.py [create_delete_table_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py +[insert_delete_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py +[insert_delete_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py -[detect_language]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_detect_language.py -[detect_language_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py -[recognize_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_entities.py -[recognize_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py -[recognize_linked_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_linked_entities.py -[recognize_linked_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py -[recognize_pii_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_pii_entities.py -[recognize_pii_entities_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py -[extract_key_phrases]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_key_phrases.py -[extract_key_phrases_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py -[analyze_sentiment]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment.py -[analyze_sentiment_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py -[get_detailed_diagnostics_information]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_get_detailed_diagnostics_information.py -[get_detailed_diagnostics_information_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_get_detailed_diagnostics_information_async.py -[sample_alternative_document_input]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_alternative_document_input.py -[sample_alternative_document_input_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_alternative_document_input_async.py -[sample_analyze_sentiment_with_opinion_mining]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment_with_opinion_mining.py -[sample_analyze_sentiment_with_opinion_mining_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_with_opinion_mining_async.py -[pip]: https://pypi.org/project/pip/ -[azure_subscription]: https://azure.microsoft.com/free/ -[azure_text_analytics_account]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=singleservice%2Cwindows -[azure_identity_pip]: https://pypi.org/project/azure-identity/ -[api_reference_documentation]: https://aka.ms/azsdk-python-textanalytics-ref-docs \ No newline at end of file +[query_table]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py +[query_table_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py diff --git a/sdk/tables/azure-data-tables/samples/create_query_entities.py b/sdk/tables/azure-data-tables/samples/create_query_entities.py deleted file mode 100644 index 108f4e326b4d..000000000000 --- a/sdk/tables/azure-data-tables/samples/create_query_entities.py +++ /dev/null @@ -1,32 +0,0 @@ -import os - -class CreateODataQuery(object): - connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") - access_key = os.getenv("AZURE_TABLES_KEY") - account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") - account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") - table_name = "OfficeSupplies" - - entity_name = "marker" - - name_filter = "EntityName eq '{}'".format(entity_name) - - @classmethod - def sample_query_entities(self): - - from azure.data.tables import TableClient - from azure.core.exceptions import HttpResponseError - - table_client = TableClient.from_connection_string(self.connection_string, self.table_name) - - try: - queried_entities = table_client.query_entities(filter=self.name_filter, select="brand,color") - - for entity_chosen in queried_entities: - print(entity_chosen) - - except HttpResponseError as e: - print(e.message) - -if __name__ == '__main__': - CreateODataQuery.sample_query_entities() \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py b/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py index ae8770d15e3c..893ab9c1e0cf 100644 --- a/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py +++ b/sdk/tables/azure-data-tables/samples/sample_create_delete_table_async.py @@ -41,6 +41,7 @@ async def main(): await sample.create_table() await sample.delete_table() + if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py b/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py similarity index 69% rename from sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py rename to sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py index 246b03099ca5..2ac7ebdbe946 100644 --- a/sdk/tables/azure-data-tables/samples/inserting_deleting_entities.py +++ b/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py @@ -7,7 +7,6 @@ class InsertDeleteEntity(object): account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") table_name = "OfficeSupplies" - # Assuming there is a created table entity = { 'PartitionKey': 'color', 'RowKey': 'brand', @@ -17,32 +16,34 @@ class InsertDeleteEntity(object): } def create_entity(self): - from azure.data.tables import TableClient - from azure.core.exceptions import ResourceExistsError + from azure.core.exceptions import ResourceExistsError, HttpResponseError - # table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) table_client = TableClient.from_connection_string(self.connection_string, self.table_name) + # Create a table in case it does not already exist try: - inserted_entity = table_client.create_entity(entity=self.entity) + table_client.create_table() + except HttpResponseError: + print("Table already exists") - print(inserted_entity.items()) # print out key-value pair of entity + try: + entity = table_client.create_entity(entity=self.entity) + print(entity) # print out key-value pair of entity except ResourceExistsError: print("Entity already exists") - def delete_entity(self): + def delete_entity(self): from azure.data.tables import TableClient from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError from azure.core import MatchConditions - # table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) - table_client = TableClient.from_connection_string(self.connection_string, self.table_name) + table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) # Create entity to delete (to showcase etag) try: - entity_created = table_client.create_entity(entity=self.entity) + resp = table_client.create_entity(entity=self.entity) except ResourceExistsError as e: print("Entity already exists!") @@ -50,7 +51,6 @@ def delete_entity(self): # will delete if match_condition and etag are satisfied table_client.delete_entity(row_key=self.entity["RowKey"], partition_key=self.entity["PartitionKey"]) print("Successfully deleted!") - except ResourceNotFoundError: print("Entity does not exists") diff --git a/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py b/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py new file mode 100644 index 000000000000..6345e6d73568 --- /dev/null +++ b/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities_async.py @@ -0,0 +1,67 @@ +import os +import asyncio + +class InsertDeleteEntity(object): + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" + + entity = { + 'PartitionKey': 'color', + 'RowKey': 'brand', + 'text': 'Marker', + 'color': 'Purple', + 'price': '5' + } + + 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 + try: + await table_client.create_table() + except HttpResponseError: + print("Table already exists") + + try: + entity = await table_client.create_entity(entity=self.entity) + print(entity) # print out key-value pair of entity + except ResourceExistsError: + print("Entity already exists") + + + async def delete_entity(self): + from azure.data.tables.aio import TableClient + from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError + from azure.core import MatchConditions + + table_client = TableClient(account_url=self.account_url, credential=self.access_key, table_name=self.table_name) + + # Create entity to delete (to showcase etag) + try: + resp = await table_client.create_entity(entity=self.entity) + except ResourceExistsError as e: + print("Entity already exists!") + + try: + # will delete if match_condition and etag are satisfied + 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 def main(): + ide = InsertDeleteEntity() + await ide.create_entity() + await ide.delete_entity() + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) diff --git a/sdk/tables/azure-data-tables/samples/sample_query_table.py b/sdk/tables/azure-data-tables/samples/sample_query_table.py new file mode 100644 index 000000000000..86ddc4ab2857 --- /dev/null +++ b/sdk/tables/azure-data-tables/samples/sample_query_table.py @@ -0,0 +1,59 @@ +import os +import copy +import random + +class SampleTablesQuery(object): + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" + + entity_name = "marker" + + name_filter = "Name eq '{}'".format(entity_name) + + def _insert_random_entities(self): + from azure.data.tables 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) + 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) + table_client.create_entity(entity=e) + + + def sample_query_entities(self): + self._insert_random_entities() + from azure.data.tables import TableClient + from azure.core.exceptions import HttpResponseError + + table_client = TableClient.from_connection_string(self.connection_string, self.table_name) + + try: + queried_entities = table_client.query_entities(filter=self.name_filter, select=["Brand","Color"]) + + for entity_chosen in queried_entities: + print(entity_chosen) + + except HttpResponseError as e: + print(e.message) + + finally: + table_client.delete_table() + +if __name__ == '__main__': + stq = SampleTablesQuery() + stq.sample_query_entities() \ No newline at end of file diff --git a/sdk/tables/azure-data-tables/samples/sample_query_table_async.py b/sdk/tables/azure-data-tables/samples/sample_query_table_async.py new file mode 100644 index 000000000000..c0bd4e7ead74 --- /dev/null +++ b/sdk/tables/azure-data-tables/samples/sample_query_table_async.py @@ -0,0 +1,70 @@ +import os +import copy +import random +import asyncio + +class SampleTablesQuery(object): + connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") + access_key = os.getenv("AZURE_TABLES_KEY") + account_url = os.getenv("AZURE_TABLES_ACCOUNT_URL") + account_name = os.getenv("AZURE_TABLES_ACCOUNT_NAME") + table_name = "OfficeSupplies" + + entity_name = "marker" + + name_filter = "Name eq '{}'".format(entity_name) + + 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) + + 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) + try: + await table_client.create_entity(entity=e) + except: + # If the value is already in the table, skip and try again + i -= 1 + pass + + + 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) + + try: + queried_entities = table_client.query_entities(filter=self.name_filter, select=["Brand","Color"]) + + for entity_chosen in queried_entities: + print(entity_chosen) + + except HttpResponseError as e: + print(e.message) + + finally: + await table_client.delete_table() + + +async def main(): + stq = SampleTablesQuery() + await stq.sample_query_entities() + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) \ No newline at end of file