Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update samples #1

Merged
merged 4 commits into from
Aug 24, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
added more files (copies for async), and a README to the samples portion
  • Loading branch information
seankane-msft committed Aug 24, 2020
commit 7a628ea7df6caa9ad6c5497b8586bbc059919e77
59 changes: 36 additions & 23 deletions sdk/tables/azure-data-tables/samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.


<!-- LINKS -->
[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
[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
32 changes: 0 additions & 32 deletions sdk/tables/azure-data-tables/samples/create_query_entities.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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())
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -17,40 +16,41 @@ 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!")

try:
# 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")

Expand Down
Original file line number Diff line number Diff line change
@@ -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())
59 changes: 59 additions & 0 deletions sdk/tables/azure-data-tables/samples/sample_query_table.py
Original file line number Diff line number Diff line change
@@ -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()
70 changes: 70 additions & 0 deletions sdk/tables/azure-data-tables/samples/sample_query_table_async.py
Original file line number Diff line number Diff line change
@@ -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())