Skip to content

Commit

Permalink
Packaging update of azure-data-tables
Browse files Browse the repository at this point in the history
  • Loading branch information
AutorestCI committed Aug 31, 2020
1 parent efb41da commit 5f98393
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 290 deletions.
4 changes: 1 addition & 3 deletions sdk/tables/azure-data-tables/MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@ recursive-include tests *.py *.yaml
include *.md
include azure/__init__.py
include azure/data/__init__.py
include LICENSE.txt
recursive-include tests *.py
recursive-include samples *.py *.md

285 changes: 9 additions & 276 deletions sdk/tables/azure-data-tables/README.md
Original file line number Diff line number Diff line change
@@ -1,288 +1,21 @@
# Azure Data Tables client library for Python
# Microsoft Azure SDK for Python

Azure Data Tables is a NoSQL data storing service that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS.
Tables scale as needed to support the amount of data inserted, and allow for the storing of data with non-complex accessing.
The Azure Data Tables client can be used to access Azure Storage or Cosmos accounts.
This is the Microsoft Azure MyService Management Client Library.
This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8.
For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all).


# Usage
* Storing structured data in the form of tables # Usage
* Quickly querying data using a clustered index

[Source code](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk) | [Package (PyPI)](https://pypi.org) | [API reference documentation](https://aka.ms/azsdk/python/tables/docs) | [Product documentation](https://docs.microsoft.com/azure/storage/) | [Samples](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk)
For code examples, see [MyService Management](https://docs.microsoft.com/python/api/overview/azure/)
on docs.microsoft.com.

## Getting started

### 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).
# Provide Feedback

### Install the package
Install the Azure Data Tables client library for Python with [pip](https://pypi.org/project/pip/):
If you encounter any bugs or have suggestions, please file an issue in the
[Issues](https://github.com/Azure/azure-sdk-for-python/issues)
section of the project.

```bash
pip install --pre azure-data-tables
```

### Create a storage account
If you wish to create a new cosmos storage account, you can use the [Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal)
If you wish to create a new storage account, you can use the
[Azure Portal](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal),
[Azure PowerShell](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-powershell),
or [Azure CLI](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-cli):

```bash
# Create a new resource group to hold the storage account -
# if using an existing resource group, skip this step
az group create --name MyResourceGroup --location westus2
# Create the storage account
az storage account create -n mystorageaccount -g MyResourceGroup
```

### Create the client
The Azure Data Tables client library for Python allows you to interact with two types of resources: the
account and tables, and entities. Interaction with these resources starts with an instance of a [client](#clients).
To create a client object, you will need the account's table service endpoint URL and a credential that allows
you to access the account:

```python
from azure.data.tables import TableServiceClient
service = TableServiceClient(account_url="https://<myaccount>.table.core.windows.net/", credential=credential)
```

#### Looking up the account URL
You can find the account's table service URL using the
[Azure Portal](https://docs.microsoft.com/azure/storage/common/storage-account-overview#storage-account-endpoints),
[Azure PowerShell](https://docs.microsoft.com/powershell/module/az.storage/get-azstorageaccount),
or [Azure CLI](https://docs.microsoft.com/cli/azure/storage/account?view=azure-cli-latest#az-storage-account-show):

```bash
# Get the table service URL for the account
az storage account show -n mystorageaccount -g MyResourceGroup --query "primaryEndpoints.table"
```

#### Types of credentials
The `credential` parameter may be provided in a number of different forms, depending on the type of
[authorization](https://docs.microsoft.com/azure/storage/common/storage-auth) you wish to use:
1. To use a [shared access signature (SAS) token](https://docs.microsoft.com/azure/storage/common/storage-sas-overview),
provide the token as a string. If your account URL includes the SAS token, omit the credential parameter.
You can generate a SAS token from the Azure Portal under "Shared access signature" or use one of the `generate_sas()`
functions to create a sas token for the account or table:

```python
from datetime import datetime, timedelta
from azure.data.tables import TableServiceClient, generate_account_sas, ResourceTypes, AccountSasPermissions

sas_token = generate_account_sas(
account_name="<account-name>",
account_key="<account-access-key>",
resource_types=ResourceTypes(service=True),
permission=AccountSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1)
)

table_service_client = TableServiceClient(account_url="https://<my_account_name>.table.core.windows.net", credential=sas_token)
```

2. To use an account [shared key](https://docs.microsoft.com/rest/api/storageservices/authenticate-with-shared-key/)
(aka account key or access key), provide the key as a string. This can be found in the Azure Portal under the "Access Keys"
section or by running the following Azure CLI command:

```az storage account keys list -g MyResourceGroup -n mystorageaccount```
Use the key as the credential parameter to authenticate the client:
```python
from azure.data.tables import TableServiceClient
service = TableServiceClient(account_url="https://<my_account_name>.table.core.windows.net", credential="<account_access_key>")
```

#### Creating the client from a connection string
Depending on your use case and authorization method, you may prefer to initialize a client instance with a
connection string instead of providing the account URL and credential separately. To do this, pass the
connection string to the client's `from_connection_string` class method:

```python
from azure.data.tables import TableServiceClient
connection_string = "DefaultEndpointsProtocol=https;AccountName=xxxx;AccountKey=xxxx;EndpointSuffix=core.windows.net"
service = TableServiceClient.from_connection_string(conn_str=connection_string)
```

The connection string to your account can be found in the Azure Portal under the "Access Keys" section or by running the following CLI command:

```bash
az storage account show-connection-string -g MyResourceGroup -n mystorageaccount
```

## Key concepts
The following components make up the Azure Data Tables Service:
* The account
* A table within the account, which contains a set of entities
* An entity within a table, as a dictionary

The Azure Data Tables client library for Python allows you to interact with each of these components through the
use of a dedicated client object.

### Clients
Two different clients are provided to to interact with the various components of the Table Service:
1. [TableServiceClient](https://aka.ms/azsdk/python/tables/docs) -
this client represents interaction with the Azure account itself, and allows you to acquire preconfigured
client instances to access the tables within. It provides operations to retrieve and configure the account
properties as well as query, create, and delete tables within the account. To perform operations on a specific table,
retrieve a client using the `get_table_client` method.
2. [TableClient](https://aka.ms/azsdk/python/tables/docs) -
this client represents interaction with a specific table (which need not exist yet). It provides operations to
create, delete, or update a table and includes operations to query, get, and upsert entities
within it.

### Entities
* **Create** - Adds an entity to the table.
* **Delete** - Deletes an entity from the table.
* **Update** - Updates an entities information by either merging or replacing the existing entity.
* **Query** - Queries existing entities in a table based off of the QueryOptions (OData).
* **Get** - Gets a specific entity from a table by partition and row key.
* **Upsert** - Merges or replaces an entity in a table, or if the entity does not exist, inserts the entity.

## Examples

The following sections provide several code snippets covering some of the most common Table tasks, including:

* [Creating a table](#creating-a-table "Creating a table")
* [Creating entities](#creating-entities "Creating entities")
* [Querying entities](#querying-entities "Querying entities")


### Creating a table
Create a table in your account

```python
from azure.data.tables import TableServiceClient
table_service_client = TableServiceClient.from_connection_string(conn_str="<connection_string>")
table_service_client.create_table(table_name="myTable")
```

### Creating entities
Create entities in the table

```python
from azure.data.tables import TableClient
my_entity = {'PartitionKey':'part','RowKey':'row'}
table_client = TableClient.from_connection_string(conn_str="<connection_string>", table_name="myTable")
entity = table_client.create_entity(entity=my_entity)
```

### Querying entities
Querying entities in the table

```python
from azure.data.tables import TableClient
my_filter = "text eq Marker"
table_client = TableClient.from_connection_string(conn_str="<connection_string>", table_name="mytable")
entity = table_client.query_entities(filter=my_filter)
```

## Optional Configuration

Optional keyword arguments can be passed in at the client and per-operation level. The azure-core [reference documentation](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html) describes available configurations for retries, logging, transport protocols, and more.


### Retry Policy configuration

Use the following keyword arguments when instantiating a client to configure the retry policy:

* __retry_total__ (int): Total number of retries to allow. Takes precedence over other counts.
Pass in `retry_total=0` if you do not want to retry on requests. Defaults to 10.
* __retry_connect__ (int): How many connection-related errors to retry on. Defaults to 3.
* __retry_read__ (int): How many times to retry on read errors. Defaults to 3.
* __retry_status__ (int): How many times to retry on bad status codes. Defaults to 3.
* __retry_to_secondary__ (bool): Whether the request should be retried to secondary, if able.
This should only be enabled of RA-GRS accounts are used and potentially stale data can be handled.
Defaults to `False`.

### Other client / per-operation configuration

Other optional configuration keyword arguments that can be specified on the client or per-operation.

**Client keyword arguments:**

* __connection_timeout__ (int): Optionally sets the connect and read timeout value, in seconds.
* __transport__ (Any): User-provided transport to send the HTTP request.

**Per-operation keyword arguments:**

* __raw_response_hook__ (callable): The given callback uses the response returned from the service.
* __raw_request_hook__ (callable): The given callback uses the request before being sent to service.
* __client_request_id__ (str): Optional user specified identification of the request.
* __user_agent__ (str): Appends the custom value to the user-agent header to be sent with the request.
* __logging_enable__ (bool): Enables logging at the DEBUG level. Defaults to False. Can also be passed in at
the client level to enable it for all requests.
* __headers__ (dict): Pass in custom headers as key, value pairs. E.g. `headers={'CustomValue': value}`


## Troubleshooting
### General
Azure Data Tables clients raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/README.md).
All Table service operations will throw a `HttpResponseError` on failure with helpful [error codes](https://docs.microsoft.com/rest/api/storageservices/table-service-error-codes).

### Logging
This library uses the standard
[logging](https://docs.python.org/3/library/logging.html) library for logging.
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
level.

Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with the `logging_enable` argument:
```python
import sys
import logging
from azure.data.tables import TableServiceClient
# Create a logger for the 'azure.data.tables' SDK
logger = logging.getLogger('azure.data.tables')
logger.setLevel(logging.DEBUG)
# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
# This client will log detailed information about its HTTP sessions, at DEBUG level
service_client = TableServiceClient.from_connection_string("your_connection_string", logging_enable=True)
```

Similarly, `logging_enable` can enable detailed logging for a single operation,
even when it isn't enabled for the client:
```py
service_client.get_service_stats(logging_enable=True)
```

## Next steps

Get started with our [Table samples](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk).

Several Azure Data Tables Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Tables:

* [table_samples_authentication.py](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk) - Examples found in this article:
* From a connection string
* From a shared access key
* From a shared access signature token
* [table_samples_service.py](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk) - Examples found in this article:
* Get and set service properties
* List tables in a account
* Create and delete a table from the service
* Get the TableClient
* [table_samples_client.py](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk) - Examples found in this article:
* Client creation
* Create a table
* Create and Delete entities
* Query entities
* Update entities
* Upsert entities

### Additional documentation
For more extensive documentation on Azure Data Tables, see the [Azure Data Tables documentation](https://docs.microsoft.com/azure/storage/tables/) on docs.microsoft.com.

## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-data-tables%2FREADME.png)
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__)
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__)
18 changes: 9 additions & 9 deletions sdk/tables/azure-data-tables/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

# Change the PACKAGE_NAME only to change folder and different name
PACKAGE_NAME = "azure-data-tables"
PACKAGE_PPRINT_NAME = "Azure Data Tables"
PACKAGE_PPRINT_NAME = "MyService Management"

# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
Expand All @@ -36,8 +36,11 @@
pass

# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) # type: ignore
with open(os.path.join(package_folder_path, 'version.py')
if os.path.exists(os.path.join(package_folder_path, 'version.py'))
else os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)

if not version:
raise RuntimeError('Cannot find version information')
Expand All @@ -56,7 +59,7 @@
license='MIT License',
author='Microsoft Corporation',
author_email='azpysdkhelp@microsoft.com',
url='https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/table/azure-table',
url='https://github.com/Azure/azure-sdk-for-python',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
Expand All @@ -77,14 +80,11 @@
'azure.data',
]),
install_requires=[
'azure-core<2.0.0,>=1.2.2',
'msrest>=0.6.10',
'msrest>=0.5.0',
'msrestazure>=0.4.32,<2.0.0',
'azure-common~=1.1',
],
extras_require={
":python_version<'3.0'": ['futures'],
":python_version<'3.4'": ['enum34>=1.0.4'],
":python_version<'3.5'": ["typing"]
":python_version<'3.0'": ['azure-data-nspkg'],
}
)

0 comments on commit 5f98393

Please sign in to comment.