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 readme samples #13486

Merged
merged 34 commits into from
Sep 4, 2020
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
4c15e4e
updated each sample to use env variables, more informative print stat…
seankane-msft Aug 19, 2020
998a1e4
updating readme with more accurate links, still missing a few
seankane-msft Aug 21, 2020
6e986a9
grammar fixes
seankane-msft Aug 21, 2020
ca60662
Merge branch 'master' of https://github.com/Azure/azure-sdk-for-pytho…
seankane-msft Aug 24, 2020
75c7982
added a readme, and async versions for auth and create/delete operations
seankane-msft Aug 24, 2020
7a628ea
added more files (copies for async), and a README to the samples portion
seankane-msft Aug 24, 2020
c07cb87
basic commit, merging others into one branch
seankane-msft Aug 24, 2020
b8a7d0a
Merge pull request #1 from seankane-msft/update-samples
seankane-msft Aug 24, 2020
4083729
Merge pull request #2 from seankane-msft/update-readme
seankane-msft Aug 24, 2020
ac9ae75
put async into another folder
seankane-msft Aug 24, 2020
f21354b
more README updates to align with .NET
seankane-msft Sep 1, 2020
9152981
initial draft of README and samples
seankane-msft Sep 1, 2020
8b16b84
initial comments from cala and kate
seankane-msft Sep 2, 2020
eccb1e9
merge conflict on readme
seankane-msft Sep 2, 2020
d3ee484
merge conflict #2
seankane-msft Sep 2, 2020
50e9b78
caught a text analytics reference, thanks kate
seankane-msft Sep 2, 2020
5c9de9c
caught a text analytics reference, thanks kate
seankane-msft Sep 2, 2020
3cb30d2
reverting version
seankane-msft Sep 2, 2020
3dd5e43
fixing two broken links
seankane-msft Sep 2, 2020
432282f
recording for test_list_tables that got left out
seankane-msft Sep 2, 2020
1dfcff9
fixing broken links
seankane-msft Sep 2, 2020
2e96610
another attempt at broken links
seankane-msft Sep 2, 2020
f6961a2
changing parentheses to a bracket per kristas recommendation
seankane-msft Sep 3, 2020
3626f6c
commenting out one test with weird behavior
seankane-msft Sep 3, 2020
01e1ab4
re-run recordings for conflicts
seankane-msft Sep 3, 2020
4f4b468
found an actual broken link
seankane-msft Sep 3, 2020
b6e0b4e
lint fixes
seankane-msft Sep 3, 2020
37c8b6a
update to readme and samples per cala, issy, and kates recs. added ex…
seankane-msft Sep 3, 2020
2613312
added a quote around odata filter, thanks Chris for the catch
seankane-msft Sep 3, 2020
e6bd86b
updating a few more broken links
seankane-msft Sep 3, 2020
a3be3a6
adding an aka.ms link for pypi
seankane-msft Sep 3, 2020
35a1615
two more broken links
seankane-msft Sep 3, 2020
fe8e23b
reverting a change back
seankane-msft Sep 3, 2020
fa1fb92
fixing missing END statements, removing link to nowhere, correcting l…
seankane-msft Sep 3, 2020
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
184 changes: 123 additions & 61 deletions sdk/tables/azure-data-tables/README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion sdk/tables/azure-data-tables/azure/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: str
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
2 changes: 1 addition & 1 deletion sdk/tables/azure-data-tables/azure/data/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: str
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
81 changes: 81 additions & 0 deletions sdk/tables/azure-data-tables/samples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
page_type: sample
languages:
- python
products:
- azure
- azure-table-storage
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
urlFragment: tables-samples
---

# Samples for Azure Tables client library for Python

These code samples show common scenario operations with the Azure Data Tables 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 Tables client's offerings.

|**File Name**|**Description**|
|-------------|---------------|
|[sample_authentication.py][sample_authentication] and [sample_authentication_async.py][sample_authentication_async]|Different authorization methods|
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
|[sample_create_client.py][create_client] and [sample_create_client_async.py][create_client_async]|Instantiate a table client|Authorizing a `TableServiceClient` object and `TableClient` 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|
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
|[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|
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
|[sample_query_tables.py][query_tables] and [sample_query_tables_async.py][query_tables_async]|Querying tables in a storage account|
|[sample_update_upsert_merge_entities.py][update_upsert_merge] and [sample_update_upsert_merge_entities_async.py][update_upsert_merge_async]| Updating, upserting, and merging entities|


### 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
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
[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_create_table.py`

## Next steps

Check out the [API reference documentation][api_reference_documentation] to learn more about
what you can do with the Azure Data Tables 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/sample_authentication.py
[sample_authentication_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/async_samples/sample_authentication_async.py

[create_client]:https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_create_client.py
[create_client_async]:https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/async_samples/sample_create_client_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/async_samples/sample_create_delete_table_async.py

[insert_delete_entities]: 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/async_samples/sample_insert_delete_entities_async.py

[query_entities]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_query_table.py
[query_table_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/async_samples/sample_query_table_async.py

[query_tables]:https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_query_tables.py
[query_tables_async]:https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/async_samples/sample_query_tables_async.py

[update_upsert_merge]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py
[update_upsert_merge_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables/azure-data-tables/samples/async_samples/sample_update_upsert_merge_entities_async.py
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python/sdk/tables/azure-data-tables/README.png)
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# 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]
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
from azure.data.tables.aio import TableServiceClient
table_service = TableServiceClient.from_connection_string(conn_str=self.connection_string)
properties = await 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 = await 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
print(self.account_name)
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__':
asyncio.run(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# 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 CreateClients(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")
my_table = os.getenv("AZURE_TABLES_NAME") or ""

async def create_table_client(self):
# Instantiate a TableServiceClient using a connection string
# [START create_table_client]
from azure.data.tables.aio import TableClient
table_client = TableClient.from_connection_string(
conn_str=self.connection_string,
table_name="tableName"
)
print("Table name: {}".format(table_client.table_name))
# [END create_table_client]

async def create_table_service_client(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 = await table_service.get_service_properties()
print("Properties: {}".format(properties))
# [END create_table_service_client]


async def main():
sample = CreateClients()
await sample.create_table_client()
await sample.create_table_service_client()


if __name__ == '__main__':
asyncio.run(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
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_item = await table_service_client.create_table(table_name=self.table_name)
print("Created table {}!".format(table_item.table_name))
except ResourceExistsError:
print("Table already exists")

async def create_if_not_exists(self):
from azure.data.tables.aio import TableServiceClient

table_service_client = TableServiceClient.from_connection_string(self.connection_string)
table_item = TableServiceClient.create_table_if_not_exists(table_name=self.table_name)
print("Table name: {}".format(table_item.table_name))


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 create_from_table_client(self):
from azure.data.table import TableClient

table_client = TableClient.from_connection_string(
conn_str=self.connection_string,
table_name=self.table_name
)
try:
table_item = await table_client.create_table()
print("Created table {}!".format(table_item.table_name))
except ResourceExistsError:
print("Table already exists")


async def delete_from_table_client(self):
from azure.data.table import TableClient

table_client = TableClient.from_connection_string(
conn_str=self.connection_string,
table_name=self.table_name
)
try:
await table_client.delete_table()
print("Deleted table {}!".format(self.table_name))
except ResourceExistsError:
print("Table already exists")


async def main():
sample = CreateDeleteTable()
seankane-msft marked this conversation as resolved.
Show resolved Hide resolved
await sample.create_table()
await sample.delete_table()


if __name__ == '__main__':
asyncio.run(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
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)
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:
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__':
asyncio.run(main())
Loading