# packages

pkgId: 6f212faf85c1db968f0a9a16c835c189d45db13499df03576988a999ab51ddda
name: python-azure-core-tracing-opencensus
arch: src
version: 1.0.0b10
epoch: 0
release: 1
summary: Microsoft Azure Azure Core Opencensus plugin Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core-tracing-opencensus
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-core-tracing-opencensus-1.0.0b10-1.src.rpm
checksum_type: sha256
description:
  This package has been deprecated and will no longer be maintained after 11-05-2024.

  Please use the [Azure Core Tracing OpenTelemetry](https://pypi.org/project/azure-core-tracing-opentelemetry/) package for tracing support in Azure SDK libraries.








  - This package has been deprecated and will no longer be maintained after 11-05-2024. Use the [azure-core-tracing-opentelemetry](https://pypi.org/project/azure-core-tracing-opentelemetry/) package for tracing support in Azure SDK libraries.





  - Fixed a bug where starting a span would fail if an unexpected keyword argument was passed in to `OpenCensusSpan`.



  - Python 2.7 is no longer supported. Please use Python version 3.7 or later.



  - Fix for supporting `kind` keyword while instantiating the span.



  - `Link` and `SpanKind` can now be added while creating the span instance.



  - `link` and `link_from_headers` now accept attributes.





  - Fix context passing for multi-threading
  - Don't fail on unknown span type, but maps to PRODUCER or UNSPECIFIED



  - Implement new "change_context" API





  - Opencensus implementation of azure-core tracing protocol


pkgId: ccc2285331e095ec45cd998eb253f1a70e915754a7ea7025eba9ad52682735ca
name: python-azure-core-tracing-opencensus
arch: src
version: 1.0.0b9
epoch: 0
release: 1
summary: Microsoft Azure Azure Core Opencensus plugin Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core-tracing-opencensus
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-core-tracing-opencensus-1.0.0b9-1.src.rpm
checksum_type: sha256
description:
  Install the opencensus python for Python with [pip](https://pypi.org/project/pip/):

  ```bash
  pip install azure-core-tracing-opencensus --pre
  ```

  Now you can use opencensus for Python as usual with any SDKs that is compatible
  with azure-core tracing. This includes (not exhaustive list), azure-storage-blob, azure-keyvault-secrets, azure-eventhub, etc.



  * You don't need to pass any context, SDK will get it for you
  * The opencensus threading plugin is installed with this package



  There is no explicit context to pass, you just create your usual opencensus and tracer and
  call any SDK code that is compatible with azure-core tracing. This is an example
  using Azure Monitor exporter, but you can use any exporter (Zipkin, etc.).

  ```python
  from opencensus.ext.azure.trace_exporter import AzureExporter

  from opencensus.trace.tracer import Tracer
  from opencensus.trace.samplers import AlwaysOnSampler

  from azure.storage.blob import BlobServiceClient

  exporter = AzureExporter(
      instrumentation_key="uuid of the instrumentation key (see your Azure Monitor account)"
  )

  tracer = Tracer(exporter=exporter, sampler=AlwaysOnSampler())
  with tracer.span(name="MyApplication") as span:
      client = BlobServiceClient.from_connection_string('connectionstring')
      client.delete_container('my_container')  # Call will be traced
  ```




  This client raises exceptions defined in [Azure Core](https://docs.microsoft.com/python/api/azure-core/azure.core.exceptions?view=azure-python).




  More documentation on OpenCensus configuration can be found on the [OpenCensus website](https://opencensus.io)



  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.








  - Fixed a bug where starting a span would fail if an unexpected keyword argument was passed in to `OpenCensusSpan`.



  - Python 2.7 is no longer supported. Please use Python version 3.7 or later.



  - Fix for supporting `kind` keyword while instantiating the span.



  - `Link` and `SpanKind` can now be added while creating the span instance.



  - `link` and `link_from_headers` now accept attributes.





  - Fix context passing for multi-threading
  - Don't fail on unknown span type, but maps to PRODUCER or UNSPECIFIED



  - Implement new "change_context" API





  - Opencensus implementation of azure-core tracing protocol


pkgId: 84ddbcc12df9b0b9d13f96b0d46f7cefed161c5f2ef43bfda348a024661a8e5a
name: python-azure-core-tracing-opentelemetry
arch: src
version: 1.0.0b11
epoch: 0
release: 1
summary: Microsoft Azure Azure Core OpenTelemetry plugin Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core-tracing-opentelemetry
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-core-tracing-opentelemetry-1.0.0b11-1.src.rpm
checksum_type: sha256
description:
  Install the Azure Core OpenTelemetry Tracing plugin for Python with [pip](https://pypi.org/project/pip/):

  ```bash
  pip install azure-core-tracing-opentelemetry
  ```

  Now you can use OpenTelemetry for Python as usual with any SDKs that are compatible
  with azure-core tracing. This includes (not exhaustive list), azure-storage-blob, azure-keyvault-secrets, azure-eventhub, etc.



  * You don't need to pass any context, SDK will get it for you
  * There are two ways to enable the tracing plugin in code:

    ```python
    from azure.core.settings import settings
    from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan
    settings.tracing_implementation = OpenTelemetrySpan
    ```

    or

    ```python
    from azure.core.settings import settings
    settings.tracing_implementation = "opentelemetry"
    ```

  * Alternatively, if you have the latest version of `azure-core` installed, you can also set the following environment variable to enable tracing with OpenTelemetry:

    ```bash
    AZURE_SDK_TRACING_IMPLEMENTATION=opentelemetry
    ```



  There is no explicit context to pass, you just create your usual opentelemetry tracer and
  call any SDK code that is compatible with azure-core tracing. This is an example
  using Azure Monitor exporter, but you can use any exporter (Zipkin, etc.).

  ```python


  from azure.core.settings import settings

  settings.tracing_implementation = "opentelemetry"











  from opentelemetry import trace
  from opentelemetry.sdk.trace import TracerProvider
  from opentelemetry.sdk.trace.export import ConsoleSpanExporter
  from opentelemetry.sdk.trace.export import SimpleSpanProcessor


  exporter = ConsoleSpanExporter()

  trace.set_tracer_provider(TracerProvider())
  tracer = trace.get_tracer(__name__)
  trace.get_tracer_provider().add_span_processor(
      SimpleSpanProcessor(exporter)
  )



  from azure.storage.blob import BlobServiceClient

  with tracer.start_as_current_span(name="MyApplication"):
      client = BlobServiceClient.from_connection_string('connectionstring')
      client.create_container('my_container')  # Call will be traced
  ```

  The Azure Monitor OpenTelemetry Exporter can be found in the [`azure-monitor-opentelemetry-exporter`](https://pypi.org/project/azure-monitor-opentelemetry-exporter/) package.




  With the Azure Core OpenTelemetry Tracing plugin enabled, HTTP requests made by Azure SDK clients are typically instrumented via the [`DistributedTracingPolicy`](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/azure/core/pipeline/policies/_distributed_tracing.py) automatically. Since Azure Core handles HTTP instrumentation for Azure service calls, automatic HTTP instrumentation from other libraries such as `opentelemetry-requests-instrumentation` are suppressed to avoid duplicate spans from being created.




  This client raises exceptions defined in [Azure Core](https://learn.microsoft.com/python/api/azure-core/azure.core.exceptions?view=azure-python).




  More documentation on OpenTelemetry configuration can be found on the [OpenTelemetry website](https://opentelemetry.io)




  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.








  - Fixed `OpenTelemetrySpan` typing to correctly implement the `AbstractSpan` protocol. ([#31943](https://github.com/Azure/azure-sdk-for-python/pull/31943))





  - Enabled the use of the `context` keyword argument for passing in context headers of a parent span. This will be the parent context used when creating the span. ([#30411](https://github.com/Azure/azure-sdk-for-python/pull/30411))



  - Remapped certain attributes to converge with OpenTelemetry semantic conventions ([#29203](https://github.com/Azure/azure-sdk-for-python/pull/29203)):
      - `x-ms-client-request-id` -> `az.client_request_id`,
      - `x-ms-request-id` -> `az.service_request_id`,
      - `http.user_agent` -> `user_agent.original`,
      - `message_bus.destination` -> `messaging.destination.name`,
      - `peer.address` -> `net.peer.name`,



  - Python 2.7 is no longer supported. Please use Python version 3.7 or later.
  - Nested internal spans are now suppressed with just the outermost internal span being recorded. Nested client spans will be children of the outermost span. ([#29616](https://github.com/Azure/azure-sdk-for-python/pull/29616))
  - When client spans are created, a flag is set to indicate that automatic HTTP instrumentation should be suppressed. Since azure-core already instruments HTTP calls, this prevents duplicate spans from being produced. ([#29616](https://github.com/Azure/azure-sdk-for-python/pull/29616))
  - Schema URL is now set on the tracer's instrumentation scope. ([#30014](https://github.com/Azure/azure-sdk-for-python/pull/30014))
  - Minimum `opentelemetry-api` dependency bumped to `1.12.0`.
  - Minimum `azure-core` dependency bumped to `1.24.0`.



  - Updated opentelemetry-api to version 1.0.0
  - `Link` and `SpanKind` can now be added while creating the span instance.



  - Pinned opentelemetry-api to version 0.17b0



  - Pinned opentelemetry-api to version 0.13b0



  - Pinned opentelemetry-api to version 0.10b0



  - Pinned opentelemetry-api to version 0.8b0
  - Fixed a bug where `DefaultSpan` sometimes throws an AttributeError.



  - `link` and `link_from_headers` now accepts attributes.





  - Pinned opentelemetry-api to version 0.6b0





  - Pinned opentelemetry-api to version 0.4a0





  - Opentelemetry implementation of azure-core tracing protocol


pkgId: 710daf5ea00792f3f4923bce037779078e70befbff829b335f2bd9bb337183a6
name: python-azure-cosmos
arch: src
version: 4.7.0
epoch: 0
release: 1
summary: Microsoft Azure Cosmos Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-cosmos-4.7.0-1.src.rpm
checksum_type: sha256
description:
  _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_



  Azure Cosmos DB is a globally distributed, multi-model database service that supports document, key-value, wide-column, and graph databases.

  Use the Azure Cosmos DB SQL API SDK for Python to manage databases and the JSON documents they contain in this NoSQL database service. High level capabilities are:

  * Create Cosmos DB **databases** and modify their settings
  * Create and modify **containers** to store collections of JSON documents
  * Create, read, update, and delete the **items** (JSON documents) in your containers
  * Query the documents in your database using **SQL-like syntax**

  [SDK source code][source_code]
  | [Package (PyPI)][cosmos_pypi]
  | [Package (Conda)](https://anaconda.org/microsoft/azure-cosmos/)
  | [API reference documentation][ref_cosmos_sdk]
  | [Product documentation][cosmos_docs]
  | [Samples][cosmos_samples]

  > This SDK is used for the [SQL API](https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started). For all other APIs, please check the [Azure Cosmos DB documentation](https://docs.microsoft.com/azure/cosmos-db/introduction) to evaluate the best SDK for your project.





  New releases of this SDK won't support Python 2.x starting January 1st, 2022. Please check the [CHANGELOG](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/CHANGELOG.md) for more information.



  * Azure subscription - [Create a free account][azure_sub]
  * Azure [Cosmos DB account][cosmos_account] - SQL API
  * [Python 3.6+][python]

  If you need a Cosmos DB SQL API account, you can create one with this [Azure CLI][azure_cli] command:

  ```Bash
  az cosmosdb create --resource-group <resource-group-name> --name <cosmos-account-name>
  ```



  ```bash
  pip install azure-cosmos
  ```



  Although not required, you can keep your base system and Azure SDK environments isolated from one another if you use a virtual environment. Execute the following commands to configure and then enter a virtual environment with [venv][venv]:

  ```Bash
  python3 -m venv azure-cosmosdb-sdk-environment
  source azure-cosmosdb-sdk-environment/bin/activate
  ```



  Interaction with Cosmos DB starts with an instance of the [CosmosClient][ref_cosmosclient] class. You need an **account**, its **URI**, and one of its **account keys** to instantiate the client object.

  Use the Azure CLI snippet below to populate two environment variables with the database account URI and its primary master key (you can also find these values in the Azure portal). The snippet is formatted for the Bash shell.

  ```Bash
  RES_GROUP=<resource-group-name>
  ACCT_NAME=<cosmos-db-account-name>

  export ACCOUNT_URI=$(az cosmosdb show --resource-group $RES_GROUP --name $ACCT_NAME --query documentEndpoint --output tsv)
  export ACCOUNT_KEY=$(az cosmosdb list-keys --resource-group $RES_GROUP --name $ACCT_NAME --query primaryMasterKey --output tsv)
  ```



  Once you've populated the `ACCOUNT_URI` and `ACCOUNT_KEY` environment variables, you can create the [CosmosClient][ref_cosmosclient].

  ```python
  from azure.cosmos import CosmosClient

  import os
  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  ```



  You can also authenticate a client utilizing your service principal's AAD credentials and the azure identity package.
  You can directly pass in the credentials information to ClientSecretCredential, or use the DefaultAzureCredential:
  ```python
  from azure.cosmos import CosmosClient
  from azure.identity import ClientSecretCredential, DefaultAzureCredential

  import os
  url = os.environ['ACCOUNT_URI']
  tenant_id = os.environ['TENANT_ID']
  client_id = os.environ['CLIENT_ID']
  client_secret = os.environ['CLIENT_SECRET']


  aad_credentials = ClientSecretCredential(
      tenant_id=tenant_id,
      client_id=client_id,
      client_secret=client_secret)


  aad_credentials = DefaultAzureCredential()

  client = CosmosClient(url, aad_credentials)
  ```
  Always ensure that the managed identity you use for AAD authentication has `readMetadata` permissions. <br>
  More information on how to set up AAD authentication: [Set up RBAC for AAD authentication](https://docs.microsoft.com/azure/cosmos-db/how-to-setup-rbac) <br>
  More information on allowed operations for AAD authenticated clients: [RBAC Permission Model](https://aka.ms/cosmos-native-rbac)



  Once you've initialized a [CosmosClient][ref_cosmosclient], you can interact with the primary resource types in Cosmos DB:

  * [Database][ref_database]: A Cosmos DB account can contain multiple databases. When you create a database, you specify the API you'd like to use when interacting with its documents: SQL, MongoDB, Gremlin, Cassandra, or Azure Table. Use the [DatabaseProxy][ref_database] object to manage its containers.

  * [Container][ref_container]: A container is a collection of JSON documents. You create (insert), read, update, and delete items in a container by using methods on the [ContainerProxy][ref_container] object.

  * Item: An Item is the dictionary-like representation of a JSON document stored in a container. Each Item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.

  For more information about these resources, see [Working with Azure Cosmos databases, containers and items][cosmos_resources].




  The keyword-argument `enable_cross_partition_query` accepts 2 options: `None` (default) or `True`.



  When using queries that try to find items based on an **id** value, always make sure you are passing in a string type variable. Azure Cosmos DB only allows string id values and if you use any other datatype, this SDK will return no results and no error messages.



  As of release version 4.3.0b3, if a user does not pass in an explicit consistency level to their client initialization,
  their client will use their database account's default level. Previously, the default was being set to `Session` consistency.
  If for some reason you'd like to keep doing this, you can change your client initialization to include the explicit parameter for this like shown:
  ```python
  from azure.cosmos import CosmosClient

  import os
  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY, consistency_level='Session')
  ```



  Currently, the features below are **not supported**. For alternatives options, check the **Workarounds** section below.



  * Group By queries
  * Queries with COUNT from a DISTINCT subquery: SELECT COUNT (1) FROM (SELECT DISTINCT C.ID FROM C)
  * Direct TCP Mode access
  * Continuation token support for aggregate cross-partition queries like sorting, counting, and distinct.
  Streamable queries like `SELECT * FROM WHERE` *do* support continuation tokens.
  * Change Feed: Processor
  * Change Feed: Read multiple partitions key values
  * Cross-partition ORDER BY for mixed types
  * Enabling diagnostics for async query-type methods



  * Get CollectionSizeUsage, DatabaseUsage, and DocumentUsage metrics
  * Create Geospatial Index
  * Get the connection string
  * Get the minimum RU/s of a container





  Typically, you can use [Azure Portal](https://portal.azure.com/), [Azure Cosmos DB Resource Provider REST API](https://docs.microsoft.com/rest/api/cosmos-db-resource-provider), [Azure CLI](https://docs.microsoft.com/cli/azure/azure-cli-reference-for-cosmos-db) or [PowerShell](https://docs.microsoft.com/azure/cosmos-db/manage-with-powershell) for the control plane unsupported limitations.


  While the SDK supports transactional batch, support for bulk requests is not yet implemented in the Python SDK. You can use the async client along with this [concurrency sample][cosmos_concurrency_sample] we have developed as a reference for a possible workaround.
  >[WARNING]
  > Using the asynchronous client for concurrent operations like shown in this sample will consume a lot of RUs very fast. We **strongly recommend** testing this out against the cosmos emulator first to verify your code works well and avoid incurring charges.





  While the Python language [uses](https://docs.python.org/3/library/stdtypes.html?highlight=boolean#truth-value-testing) "True" and "False" for boolean types, Cosmos DB [accepts](https://docs.microsoft.com/azure/cosmos-db/sql-query-is-bool) "true" and "false" only. In other words, the Python language uses Boolean values with the first uppercase letter and all other lowercase letters, while Cosmos DB and its SQL language use only lowercase letters for those same Boolean values. How to deal with this challenge?

  * Your JSON documents created with Python must use "True" and "False", to pass the language validation. The SDK will convert it to "true" and "false" for you. Meaning that "true" and "false" is what will be stored in Cosmos DB.
  * If you retrieve those documents with the Cosmos DB Portal's Data Explorer, you will see "true" and "false".
  * If you retrieve those documents with this Python SDK, "true" and "false" values will be automatically converted to "True" and "False".



  This SDK uses the [query_items](https://docs.microsoft.com/python/api/azure-cosmos/azure.cosmos.containerproxy?preserve-view=true&view=azure-python#query-items-query--parameters-none--partition-key-none--enable-cross-partition-query-none--max-item-count-none--enable-scan-in-query-none--populate-query-metrics-none----kwargs-) method to submit SQL queries to Azure Cosmos DB.

  Cosmos DB SQL language allows you to [get subitems by using the FROM clause](https://docs.microsoft.com/azure/cosmos-db/sql-query-from#get-subitems-by-using-the-from-clause), to reduce the source to a smaller subset. As an example, you can use `select * from Families.children` instead of `select * from Families`. But please note that:

  * For SQL queries using the `query_items` method, this SDK demands that you specify the `partition_key` or use the `enable_cross_partition_query` flag.
  * If you are getting subitems and specifying the `partition_key`, please make sure that your partition key is included in the subitems, which is not true for most of the cases.



  This is a parameter of the query_items method, an integer indicating the maximum number of items to be returned per page. The `None` value can be specified to let the service determine the optimal item count. This is the recommended configuration value, and the default behavior of this SDK when it is not set.



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

  * [Create a database](#create-a-database "Create a database")
  * [Create a container](#create-a-container "Create a container")
  * [Create an analytical store enabled container](#create-an-analytical-store-enabled-container "Create a container")
  * [Get an existing container](#get-an-existing-container "Get an existing container")
  * [Insert data](#insert-data "Insert data")
  * [Delete data](#delete-data "Delete data")
  * [Query the database](#query-the-database "Query the database")
  * [Get database properties](#get-database-properties "Get database properties")
  * [Get database and container throughputs](#get-database-and-container-throughputs "Get database and container throughputs")
  * [Modify container properties](#modify-container-properties "Modify container properties")
  * [Using the asynchronous client](#using-the-asynchronous-client "Using the asynchronous client")



  After authenticating your [CosmosClient][ref_cosmosclient], you can work with any resource in the account. The code snippet below creates a SQL API database, which is the default when no API is specified when [create_database][ref_cosmosclient_create_database] is invoked.

  ```python
  from azure.cosmos import CosmosClient, exceptions
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  try:
      database = client.create_database(DATABASE_NAME)
  except exceptions.CosmosResourceExistsError:
      database = client.get_database_client(DATABASE_NAME)
  ```



  This example creates a container with default settings. If a container with the same name already exists in the database (generating a `409 Conflict` error), the existing container is obtained instead.

  ```python
  from azure.cosmos import CosmosClient, PartitionKey, exceptions
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'

  try:
      container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"))
  except exceptions.CosmosResourceExistsError:
      container = database.get_container_client(CONTAINER_NAME)
  except exceptions.CosmosHttpResponseError:
      raise
  ```



  This example creates a container with [Analytical Store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction) enabled, for reporting, BI, AI, and Advanced Analytics with [Azure Synapse Link](https://docs.microsoft.com/azure/cosmos-db/synapse-link).

  The options for analytical_storage_ttl are:

  + 0 or Null or not informed: Not enabled.
  + -1: The data will be stored infinitely.
  + Any other number: the actual ttl, in seconds.


  ```python
  CONTAINER_NAME = 'products'
  try:
      container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"),analytical_storage_ttl=-1)
  except exceptions.CosmosResourceExistsError:
      container = database.get_container_client(CONTAINER_NAME)
  except exceptions.CosmosHttpResponseError:
      raise
  ```

  The preceding snippets also handle the [CosmosHttpResponseError][ref_httpfailure] exception if the container creation failed. For more information on error handling and troubleshooting, see the [Troubleshooting](#troubleshooting "Troubleshooting") section.



  Retrieve an existing container from the database:

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)
  ```



  To insert items into a container, pass a dictionary containing your data to [ContainerProxy.upsert_item][ref_container_upsert_item]. Each item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.

  This example inserts several items into the container, each with a unique `id`:

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  for i in range(1, 10):
      container.upsert_item({
              'id': 'item{0}'.format(i),
              'productName': 'Widget',
              'productModel': 'Model {0}'.format(i)
          }
      )
  ```



  To delete items from a container, use [ContainerProxy.delete_item][ref_container_delete_item]. The SQL API in Cosmos DB does not support the SQL `DELETE` statement.

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  for item in container.query_items(
          query='SELECT * FROM products p WHERE p.productModel = "Model 2"',
          enable_cross_partition_query=True):
      container.delete_item(item, partition_key='Widget')
  ```

  > NOTE: If you are using partitioned collection, the value of the `partitionKey` in the example code above, should be set to the value of the partition key for this particular item, not the name of the partition key column in your collection. This holds true for both point reads and deletes.



  A Cosmos DB SQL API database supports querying the items in a container with [ContainerProxy.query_items][ref_container_query_items] using SQL-like syntax.

  This example queries a container for items with a specific `id`:

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)


  import json
  for item in container.query_items(
          query='SELECT * FROM mycontainer r WHERE r.id="item3"',
          enable_cross_partition_query=True):
      print(json.dumps(item, indent=True))
  ```

  > NOTE: Although you can specify any value for the container name in the `FROM` clause, we recommend you use the container name for consistency.

  Perform parameterized queries by passing a dictionary containing the parameters and their values to [ContainerProxy.query_items][ref_container_query_items]:

  ```python
  discontinued_items = container.query_items(
      query='SELECT * FROM products p WHERE p.productModel = @model',
      parameters=[
          dict(name='@model', value='Model 7')
      ],
      enable_cross_partition_query=True
  )
  for item in discontinued_items:
      print(json.dumps(item, indent=True))
  ```

  For more information on querying Cosmos DB databases using the SQL API, see [Query Azure Cosmos DB data with SQL queries][cosmos_sql_queries].



  Get and display the properties of a database:

  ```python
  from azure.cosmos import CosmosClient
  import os
  import json

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  properties = database.read()
  print(json.dumps(properties))
  ```



  Get and display the throughput values of a database and of a container with dedicated throughput:

  ```python
  from azure.cosmos import CosmosClient
  import os
  import json

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)


  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  db_offer = database.read_offer()
  print('Found Offer \'{0}\' for Database \'{1}\' and its throughput is \'{2}\''.format(db_offer.properties['id'], database.id, db_offer.properties['content']['offerThroughput']))


  CONTAINER_NAME = 'testContainer'
  container = database.get_container_client(CONTAINER_NAME)
  container_offer = container.read_offer()
  print('Found Offer \'{0}\' for Container \'{1}\' and its throughput is \'{2}\''.format(container_offer.properties['id'], container.id, container_offer.properties['content']['offerThroughput']))
  ```




  Certain properties of an existing container can be modified. This example sets the default time to live (TTL) for items in the container to 10 seconds:

  ```python
  from azure.cosmos import CosmosClient, PartitionKey
  import os
  import json

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  database.replace_container(
      container,
      partition_key=PartitionKey(path="/productName"),
      default_ttl=10,
  )

  container_props = container.read()
  print(json.dumps(container_props['defaultTtl']))
  ```

  For more information on TTL, see [Time to Live for Azure Cosmos DB data][cosmos_ttl].



  The asynchronous cosmos client is a separate client that looks and works in a similar fashion to the existing synchronous client. However, the async client needs to be imported separately and its methods need to be used with the async/await keywords.
  The Async client needs to be initialized and closed after usage, which can be done manually or with the use of a context manager. The example below shows how to do so manually. We don't recommend doing it this way, since it requires that you manually call __aenter__() before using the client.

  ```python
  from azure.cosmos.aio import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  DATABASE_NAME = 'testDatabase'
  CONTAINER_NAME = 'products'

  async def create_products():
      client = CosmosClient(URL, credential=KEY)
      await client.__aenter__() # this piece is important for the SDK to cache account information
      database = client.get_database_client(DATABASE_NAME)
      container = database.get_container_client(CONTAINER_NAME)
      for i in range(10):
          await container.upsert_item({
                  'id': 'item{0}'.format(i),
                  'productName': 'Widget',
                  'productModel': 'Model {0}'.format(i)
              }
          )
      await client.close() # the async client must be closed manually if it's not initialized in a with statement
  ```

  Instead of manually opening and closing the client, it is highly recommended to use the `async with` keywords. This creates a context manager that will initialize and later close the client once you're out of the statement, as well as cache important information the SDK needs. The example below shows how to do so.

  ```python
  from azure.cosmos.aio import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  DATABASE_NAME = 'testDatabase'
  CONTAINER_NAME = 'products'

  async def create_products():
      async with CosmosClient(URL, credential=KEY) as client: # the with statement will automatically initialize and close the async client
          database = client.get_database_client(DATABASE_NAME)
          container = database.get_container_client(CONTAINER_NAME)
          for i in range(10):
              await container.upsert_item({
                      'id': 'item{0}'.format(i),
                      'productName': 'Widget',
                      'productModel': 'Model {0}'.format(i)
                  }
              )
  ```



  Unlike the synchronous client, the async client does not have an `enable_cross_partition` flag in the request. Queries without a specified partition key value will attempt to do a cross partition query by default.

  Query results can be iterated, but the query's raw output returns an asynchronous iterator. This means that each object from the iterator is an awaitable object, and does not yet contain the true query result. In order to obtain the query results you can use an async for loop, which awaits each result as you iterate on the object, or manually await each query result as you iterate over the asynchronous iterator.

  Since the query results are an asynchronous iterator, they can't be cast into lists directly; instead, if you need to create lists from your results, use an async for loop or Python's list comprehension to populate a list:

  ```python
  from azure.cosmos.aio import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  async def create_lists():
      results = container.query_items(
              query='SELECT * FROM products p WHERE p.productModel = "Model 2"')

      

      item_list = []
      async for item in results:
          item_list.append(item)

      
      item_list = [item async for item in results]
      await client.close()
  ```


  An integrated cache is an in-memory cache that helps you ensure manageable costs and low latency as your request volume grows. The integrated cache has two parts: an item cache for point reads and a query cache for queries. The code snippet below shows you how to use this feature with the point read and query cache methods.

  The benefit of using this is that the point reads and queries that hit the integrated cache won't use any RUs. This means you will have a much lower per-operation cost than reads from the backend.

  [How to configure the Azure Cosmos DB integrated cache (Preview)][cosmos_configure_integrated_cache]

  ```python
  import azure.cosmos.cosmos_client as cosmos_client
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = cosmos_client.CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'testContainer'
  container = database.get_container_client(CONTAINER_NAME)

  def integrated_cache_snippet():
      item_id = body['id']
      query = 'SELECT * FROM c'

      
      container.read_item(item=item_id, partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)

      
      container.query_items(query=query,
           partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)
  ```
  For more information on Integrated Cache, see [Azure Cosmos DB integrated cache - Overview][cosmos_integrated_cache].


  Transactional batch requests allow you to send several operations to be executed at once within the same partition key.
  If all operations succeed in the order they're described within the transactional batch operation, the transaction will be committed.
  However, if any operation fails, the entire transaction is rolled back.

  Transactional batches have a limit of 100 operations per batch, and a total size limit of 1.2Mb for the
  batch operations being passed in.

  Transactional Batch operations look very similar to the singular operations apis, and are tuples containing
  (`operation_type_string`, `args_tuple`, `batch_operation_kwargs_dictionary`), with the kwargs dictionary being optional:
  ```python
  batch_operations = [
          ("create", (item_body,), kwargs),
          ("replace", (item_id, item_body), kwargs),
          ("read", (item_id,), kwargs),
          ("upsert", (item_body,), kwargs),
          ("patch", (item_id, operations), kwargs),
          ("delete", (item_id,), kwargs),
      ]
  batch_results = container.execute_item_batch(batch_operations=batch_operations, partition_key=partition_key)
  ```
  The batch operation kwargs dictionary is limited, and only takes a total of three different key values.
  In the case of wanting to use conditional patching within the batch, the use of `filter_predicate` key is available for the
  patch operation, or in case of wanting to use etags with any of the operations, the use of the `if_match_etag`/`if_none_match_etag`
  keys is available as well.
  ```python
  batch_operations = [
          ("replace", (item_id, item_body), {"if_match_etag": etag}),
          ("patch", (item_id, operations), {"filter_predicate": filter_predicate, "if_none_match_etag": etag}),
      ]
  ```

  We also have some samples showing these transactional batch operations in action with both the [sync][sample_document_mgmt]
  and [async][sample_document_mgmt_async] clients.

  If there is a failure for an operation within the batch, the SDK will raise a `CosmosBatchOperationError` letting you know which operation failed,
  as well as containing the list of failed responses for the failed request.

  For more information on Transactional Batch, see [Azure Cosmos DB Transactional Batch][cosmos_transactional_batch].


  We have added new capabilities to utilize vector embeddings and vector indexing for users to leverage vector
  search utilizing our Cosmos SDK. These two container-level configurations have to be turned on at the account-level
  before you can use them.

  Each vector embedding should have a path to the relevant vector field in your items being stored, a supported data type
  (float32, int8, uint8), the vector's dimensions, and the distance function being used for that embedding. Vectors indexed
  with the flat index type can be at most 505 dimensions. Vectors indexed with the quantizedFlat index type can be at most 4,096 dimensions.
  A sample vector embedding policy would look like this:
  ```python
  vector_embedding_policy = {
      "vectorEmbeddings": [
          {
              "path": "/vector1",
              "dataType": "float32",
              "dimensions": 256,
              "distanceFunction": "euclidean"
          },
          {
              "path": "/vector2",
              "dataType": "int8",
              "dimensions": 200,
              "distanceFunction": "dotproduct"
          },
          {
              "path": "/vector3",
              "dataType": "uint8",
              "dimensions": 400,
              "distanceFunction": "cosine"
          }
      ]
  }
  ```

  Separately, vector indexes have been added to the already existing indexing_policy and only require two fields per index:
  the path to the relevant field to be used, and the type of index from the possible options (flat or quantizedFlat).
  A sample indexing policy with vector indexes would look like this:
  ```python
  indexing_policy = {
          "automatic": True,
          "indexingMode": "consistent",
          "compositeIndexes": [
              [
                  {"path": "/numberField", "order": "ascending"},
                  {"path": "/stringField", "order": "descending"}
              ]
          ],
          "spatialIndexes": [
              {"path": "/location/*", "types": [
                  "Point",
                  "Polygon"]}
          ],
          "vectorIndexes": [
              {"path": "/vector1", "type": "flat"},
              {"path": "/vector2", "type": "quantizedFlat"}
          ]
      }
  ```
  You would then pass in the relevant policies to your container creation method to ensure these configurations are used by it.
  The operation will fail if you pass new vector indexes to your indexing policy but forget to pass in an embedding policy.
  ```python
  database.create_container(id=container_id, partition_key=PartitionKey(path="/id"),
                            indexing_policy=indexing_policy, vector_embedding_policy=vector_embedding_policy)
  ```
  ***Note: vector embeddings and vector indexes CANNOT be edited by container replace operations. They are only available directly through creation.***



  With the addition of the vector indexing and vector embedding capabilities, the SDK can now perform order by vector search queries.
  These queries specify the VectorDistance to use as a metric within the query text. These must always use a TOP or LIMIT clause within the query though,
  since vector search queries have to look through a lot of data otherwise and may become too expensive or long-running.
  Since these queries are relatively expensive, the SDK sets a default limit of 50000 max items per query - if you'd like to raise that further, you
  can use the `AZURE_COSMOS_MAX_ITEM_BUFFER_VECTOR_SEARCH` environment variable to do so. However, be advised that queries with too many vector results
  may have additional latencies associated with searching in the service.
  The query syntax for these operations looks like this:
  ```python
  VectorDistance(<embedding1>, <embedding2>, [,<exact_search>], [,<specification>])
  ```
  Embeddings 1 and 2 are the arrays of values for the relevant embeddings, `exact_search` is an optional boolean indicating whether
  to do an exact search vs. an approximate one (default value of false), and `specification` is an optional Json snippet with embedding
  specs that can include `dataType`, `dimensions` and `distanceFunction`. The specifications within the query will take precedence
  to any configurations previously set by a vector embedding policy.
  A sample vector search query would look something like this:
  ```python
      query = "SELECT TOP 10 c.title,VectorDistance(c.embedding, [{}]) AS " \
              "SimilarityScore FROM c ORDER BY VectorDistance(c.embedding, [{}])".format(embeddings_string, embeddings_string)
  ```
  Or if you'd like to add the optional parameters to the vector distance, you could do this:
  ```python
      query = "SELECT TOP 10 c.title,VectorDistance(c.embedding, [{}], true, {{'dataType': 'float32' , 'distanceFunction': 'cosine'}}) AS " \
              "SimilarityScore FROM c ORDER BY VectorDistance(c.embedding, [{}], true, {{'dataType': " \
              "'float32', 'distanceFunction': 'cosine'}})".format(embeddings_string, embeddings_string)
  ```
  The `embeddings_string` above would be your string made from your vector embeddings.
  You can find our sync samples [here][cosmos_index_sample] and our async samples [here][cosmos_index_sample_async] as well to help yourself out.

  *Note: For a limited time, if your query operates against a region or emulator that has not yet been updated the client might run into some issues
  not being able to recognize the new NonStreamingOrderBy capability that makes vector search possible.
  If this happens, you can set the `AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY` environment variable to `"True"` to opt out of this
  functionality and continue operating as usual.*





  When you interact with Cosmos DB using the Python SDK, exceptions returned by the service correspond to the same HTTP status codes returned for REST API requests:

  [HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]

  For example, if you try to create a container using an ID (name) that's already in use in your Cosmos DB database, a `409` error is returned, indicating the conflict. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.

  ```python
  try:
      database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"))
  except exceptions.CosmosResourceExistsError:
      print("""Error creating container
  HTTP status code 409: The ID (name) provided for the container is already in use.
  The container name must be unique within the database.""")

  ```


  This library uses the standard
  [logging](https://docs.python.org/3.5/library/logging.html) library for logging diagnostics.
  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.cosmos import CosmosClient


  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)


  handler = logging.StreamHandler(stream=sys.stdout)
  logger.addHandler(handler)


  client = CosmosClient(URL, credential=KEY, logging_enable=True)
  ```

  Similarly, `logging_enable` can enable detailed logging for a single operation,
  even when it isn't enabled for the client:
  ```python
  database = client.create_database(DATABASE_NAME, logging_enable=True)
  ```
  Alternatively, you can log using the CosmosHttpLoggingPolicy, which extends from the azure core HttpLoggingPolicy, by passing in your logger to the `logger` argument.
  By default, it will use the behaviour from HttpLoggingPolicy. Passing in the `enable_diagnostics_logging` argument will enable the
  CosmosHttpLoggingPolicy, and will have additional information in the response relevant to debugging Cosmos issues.
  ```python
  import logging
  from azure.cosmos import CosmosClient


  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)


  handler = logging.FileHandler(filename="azure")
  logger.addHandler(handler)



  client = CosmosClient(URL, credential=KEY, logger=logger, enable_diagnostics_logging=True)
  ```
  Similarly, logging can be enabled for a single operation by passing in a logger to the singular request.
  However, if you desire to use the CosmosHttpLoggingPolicy to obtain additional information, the `enable_diagnostics_logging` argument needs to be passed in at the client constructor.
  ```python

  client = CosmosClient(URL, credential=KEY, enable_diagnostics_logging=True)
  database = client.create_database(DATABASE_NAME, logger=logger)
  ```


  Azure Core provides the ability for our Python SDKs to use OpenTelemetry with them. The only packages that need to be installed
  to use this functionality are the following:
  ```bash
  pip install azure-core-tracing-opentelemetry
  pip install opentelemetry-sdk
  ```
  For more information on this, we recommend taking a look at this [document](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core-tracing-opentelemetry/README.md)
  from Azure Core describing how to set it up. We have also added a [sample file][telemetry_sample] to show how it can
  be used with our SDK. This works the same way regardless of the Cosmos client you are using.



  For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos DB documentation][cosmos_docs] on docs.microsoft.com.

  <!-- LINKS -->
  [azure_cli]: https://docs.microsoft.com/cli/azure
  [azure_portal]: https://portal.azure.com
  [azure_sub]: https://azure.microsoft.com/free/
  [cloud_shell]: https://docs.microsoft.com/azure/cloud-shell/overview
  [cosmos_account_create]: https://docs.microsoft.com/azure/cosmos-db/how-to-manage-database-account
  [cosmos_account]: https://docs.microsoft.com/azure/cosmos-db/account-overview
  [cosmos_container]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-containers
  [cosmos_database]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-databases
  [cosmos_docs]: https://docs.microsoft.com/azure/cosmos-db/
  [cosmos_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples
  [cosmos_pypi]: https://pypi.org/project/azure-cosmos/
  [cosmos_http_status_codes]: https://docs.microsoft.com/rest/api/cosmos-db/http-status-codes-for-cosmosdb
  [cosmos_item]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-items
  [cosmos_models]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/azure/cosmos/_models.py
  [cosmos_request_units]: https://docs.microsoft.com/azure/cosmos-db/request-units
  [cosmos_resources]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items
  [cosmos_sql_queries]: https://docs.microsoft.com/azure/cosmos-db/how-to-sql-query
  [cosmos_ttl]: https://docs.microsoft.com/azure/cosmos-db/time-to-live
  [cosmos_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/integrated-cache
  [cosmos_configure_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/how-to-configure-integrated-cache
  [python]: https://www.python.org/downloads/
  [ref_container_delete_item]: https://aka.ms/azsdk-python-cosmos-ref-delete-item
  [ref_container_query_items]: https://aka.ms/azsdk-python-cosmos-ref-query-items
  [ref_container_upsert_item]: https://aka.ms/azsdk-python-cosmos-ref-upsert-item
  [ref_container]: https://aka.ms/azsdk-python-cosmos-ref-container
  [ref_cosmos_sdk]: https://aka.ms/azsdk-python-cosmos-ref
  [ref_cosmosclient_create_database]: https://aka.ms/azsdk-python-cosmos-ref-create-database
  [ref_cosmosclient]: https://aka.ms/azsdk-python-cosmos-ref-cosmos-client
  [ref_database]: https://aka.ms/azsdk-python-cosmos-ref-database
  [ref_httpfailure]: https://aka.ms/azsdk-python-cosmos-ref-http-failure
  [sample_database_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/database_management.py
  [sample_document_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management.py
  [sample_document_mgmt_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management_async.py
  [sample_examples_misc]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/examples.py
  [source_code]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos
  [venv]: https://docs.python.org/3/library/venv.html
  [virtualenv]: https://virtualenv.pypa.io
  [telemetry_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/tracing_open_telemetry.py
  [timeouts_document]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/docs/TimeoutAndRetriesConfig.md
  [cosmos_transactional_batch]: https://learn.microsoft.com/azure/cosmos-db/nosql/transactional-batch
  [cosmos_concurrency_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/concurrency_sample.py
  [cosmos_index_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/index_management.py
  [cosmos_index_sample_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/index_management_async.py



  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.






  * Adds vector embedding policy and vector indexing policy. See [PR 34882](https://github.com/Azure/azure-sdk-for-python/pull/34882).
  * Adds support for vector search non-streaming order by queries. See [PR 35468](https://github.com/Azure/azure-sdk-for-python/pull/35468).
  * Adds support for using the start time option for change feed query API. See [PR 35090](https://github.com/Azure/azure-sdk-for-python/pull/35090).


  * Fixed a bug where change feed query in Async client was not returning all pages due to case-sensitive response headers. See [PR 35090](https://github.com/Azure/azure-sdk-for-python/pull/35090).
  * Fixed a bug when a retryable exception occurs in the first page of a query execution causing query to return 0 results. See [PR 35090](https://github.com/Azure/azure-sdk-for-python/pull/35090).






  * GA release of hierarchical partitioning, index metrics and transactional batch.


  * Keyword arguments were not being passed down for `create_container_if_not_exists()` methods. See [PR 34286](https://github.com/Azure/azure-sdk-for-python/pull/34286).


  * Made several updates to the type hints used throughout the SDK for greater detail. See [PR 33269](https://github.com/Azure/azure-sdk-for-python/pull/33269), [PR 33341](https://github.com/Azure/azure-sdk-for-python/pull/33341), [PR 33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).




  * Fixed bug with async lock not properly releasing on async global endpoint manager. see [PR 34579](https://github.com/Azure/azure-sdk-for-python/pull/34579).


  * Marked `computed_properties` keyword as provisional, un-marked `continuation_token_limit` as provisional. See [PR 34207](https://github.com/Azure/azure-sdk-for-python/pull/34207).


  This version and all future versions will require Python 3.8+.


  * Added **preview** support for Computed Properties on Python SDK (Must be enabled on the account level before it can be used). See [PR 33626](https://github.com/Azure/azure-sdk-for-python/pull/33626).


  * Made use of `response_hook` thread-safe in the sync client. See [PR 33790](https://github.com/Azure/azure-sdk-for-python/pull/33790).
  * Fixed bug with the session container not being properly maintained. See [33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).




  * Added support for capturing Index Metrics in query operations. See [PR 33034](https://github.com/Azure/azure-sdk-for-python/pull/33034).




  * Added support for Transactional Batch. See [PR 32508](https://github.com/Azure/azure-sdk-for-python/pull/32508).
  * Added **preview** support for Priority Based Throttling/Priority Based Execution (Must be enabled at the account level before it can be used). See [PR 32441](https://github.com/Azure/azure-sdk-for-python/pull/32441/).




  * Added support for Hierarchical Partitioning, also known as Subpartitioning. See [PR 31121](https://github.com/Azure/azure-sdk-for-python/pull/31121).


  * Small fix to the `offer_throughput` option in the async client's `create_database_if_not_exists` method, which was previously misspelled as `offerThroughput`.
  See [PR 32076](https://github.com/Azure/azure-sdk-for-python/pull/32076).


  * Marked the outdated `diagnostics.py` file for deprecation since we now recommend the use of our `CosmosHttpLoggingPolicy` for diagnostics.
  For more on the `CosmosHttpLoggingPolicy` see our [README](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#logging-diagnostics).




  * Fixed bug when query with DISTINCT + OFFSET/LIMIT operators returns unexpected result. See [PR 31925](https://github.com/Azure/azure-sdk-for-python/pull/31925).


  * Added additional checks for resource creation using specific characters that cause issues. See [PR 31861](https://github.com/Azure/azure-sdk-for-python/pull/31861).




  * Added support for continuation tokens for streamable cross partition queries. See [PR 31189](https://github.com/Azure/azure-sdk-for-python/pull/31189).


  * Fixed bug with async `create_database_if_not_exists` method not working when passing `offer_throughput` as an option. See [PR 31478](https://github.com/Azure/azure-sdk-for-python/pull/31478).


  * Renamed `response_continuation_token_limit_in_kb` to `continuation_token_limit` for GA. See [PR 31532](https://github.com/Azure/azure-sdk-for-python/pull/31532).




  * Added ability to limit continuation token size when querying for items. See [PR 30731](https://github.com/Azure/azure-sdk-for-python/pull/30731)


  * Fixed bug with async patch_item method. See [PR 30804](https://github.com/Azure/azure-sdk-for-python/pull/30804).




  - GA release of Patch API and Delete All Items By Partition Key




  * Added conditional patching for Patch operations. See [PR 30455](https://github.com/Azure/azure-sdk-for-python/pull/30455).


  * Fixed bug with non english locales causing an error with the RFC 1123 Date Format. See [PR 30125](https://github.com/Azure/azure-sdk-for-python/pull/30125).


  * Refactoring of our client `connection_timeout` and `request_timeout` configurations. See [PR 30171](https://github.com/Azure/azure-sdk-for-python/pull/30171).




   - Added **preview** delete all items by partition key functionality. See [PR 29186](https://github.com/Azure/azure-sdk-for-python/pull/29186). For more information on Partition Key Delete, please see [Azure Cosmos DB Partition Key Delete](https://learn.microsoft.com/azure/cosmos-db/nosql/how-to-delete-by-partition-key?tabs=python-example).
   - Added **preview** partial document update (Patch API) functionality and container methods for patching items with operations. See [PR 29497](https://github.com/Azure/azure-sdk-for-python/pull/29497). For more information on Patch, please see [Azure Cosmos DB Partial Document Update](https://learn.microsoft.com/azure/cosmos-db/partial-document-update).


  * Fixed bug in method `create_container_if_not_exists()` of async database client for unexpected kwargs being passed into `read()` method used internally. See [PR 29136](https://github.com/Azure/azure-sdk-for-python/pull/29136).
  * Fixed bug with method `query_items()` of our async container class, where partition key and cross partition headers would both be set when using partition keys. See [PR 29366](https://github.com/Azure/azure-sdk-for-python/pull/29366/).
  * Fixed bug with client not properly surfacing errors for invalid credentials and identities with insufficient permissions. Users running into 'NoneType has no attribute ConsistencyPolicy' errors when initializing their clients will now see proper authentication exceptions. See [PR 29256](https://github.com/Azure/azure-sdk-for-python/pull/29256).


  * Removed use of `six` package within the SDK.




   - Added `correlated_activity_id` for query operations.
   - Added cross regional retries for Service Unavailable/Request Timeouts for read/Query Plan operations.
   - GA release of CosmosHttpLoggingPolicy and autoscale feature.


  - Bug fix to address queries with VALUE MAX (or any other aggregate) that run into an issue if the query is executed on a container with at least one "empty" partition.




  - GA release of integrated cache functionality. For more information on integrated cache please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache).
  - Added ability to replace analytical ttl on containers. For more information on analytical ttl please see [Azure Cosmos DB analytical store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction).
  - Added `CosmosHttpLoggingPolicy` to replace `HttpLoggingPolicy` for logging HTTP sessions.
  - Added the ability to create containers and databases with autoscale properties for the sync and async clients.
  - Added the ability to update autoscale throughput properties.


  - Fixed parsing of args for overloaded `container.read()` method.
  - Fixed `validate_cache_staleness_value()` method to allow max_integrated_cache_staleness to be an integer greater than or equal to 0.
  - Fixed `__aiter__()` method by removing the async keyword.



  - GA release of Async I/O APIs, including all changes from 4.3.0b1 to 4.3.0b4.


  - Method signatures have been updated to use keyword arguments instead of positional arguments for most method options in the async client.
  - Bugfix: Automatic Id generation for items was turned on for `upsert_items()` method when no 'id' value was present in document body.
  Method call will now require an 'id' field to be present in the document body.


  - Deprecated offer-named methods in favor of their new throughput-named counterparts (`read_offer` -> `get_throughput`).
  - Marked the GetAuthorizationHeader method for deprecation since it will no longer be public in a future release.
  - Added samples showing how to configure retry options for both the sync and async clients.
  - Deprecated the `connection_retry_policy` and `retry_options` options in the sync client.
  - Added user warning to non-query methods trying to use `populate_query_metrics` options.




  - Added support for AAD authentication for the async client.
  - Added support for AAD authentication for the sync client.


  - Changed `_set_partition_key` return typehint in async client.



  >[WARNING]
  >The default `Session` consistency bugfix will impact customers whose database accounts have a `Bounded Staleness` or `Strong`
  > consistency level, and were previously not sending `Session` as a consistency_level parameter when initializing
  > their clients.
  > Default consistency level for the sync and async clients is no longer "Session" and will instead be set to the
    consistency level of the user's cosmos account setting on initialization if not passed during client initialization.
  > Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels)
  > for more details on consistency levels, or the README section on this change [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#note-on-client-consistency-levels).


  - Added new **provisional** `max_integrated_cache_staleness_in_ms` parameter to read item and query items APIs in order
    to make use of the **preview** CosmosDB integrated cache functionality [See PR #22946](https://github.com/Azure/azure-sdk-for-python/pull/22946).
    Please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache) for more details.
  - Added support for split-proof queries for the async client.


  - Default consistency level for the sync and async clients is no longer `Session` and will instead be set to the
    consistency level of the user's cosmos account setting on initialization if not passed during client initialization.
    This change will impact client application in terms of RUs and latency. Users relying on default `Session` consistency
    will need to pass it explicitly if their account consistency is different than `Session`.
    Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels) for more details.
  - Fixed invalid request body being sent when passing in `serverScript` body parameter to replace operations for trigger, sproc and udf resources.
  - Moved `is_system_key` logic in async client.
  - Fixed TypeErrors not being thrown when passing in invalid connection retry policies to the client.



  This version and all future versions will require Python 3.6+. Python 2.7 is no longer supported.
  We will also be removing support for Python 3.6 and will only support Python 3.7+ starting December 2022.


  - Added support for split-proof queries for the sync client.


  - Added async user agent for async client.




  - Added language native async i/o client.



  **Bug fixes**
  - Fixed bug where continuation token is not honored when query_iterable is used to get results by page. Issue #13265.
  - Fixed bug where resource tokens not being honored for document reads and deletes. Issue #13634.

  **New features**
  - Added support for passing partitionKey while querying changefeed. Issue #11689.



  - Added deprecation warning for "lazy" indexing mode. The backend no longer allows creating containers with this mode and will set them to consistent instead.

  **New features**
  - Added the ability to set the analytical storage TTL when creating a new container.

  **Bug fixes**
  - Fixed support for dicts as inputs for get_client APIs.
  - Fixed Python 2/3 compatibility in query iterators.
  - Fixed type hint error. Issue #12570 - thanks @sl-sandy.
  - Fixed bug where options headers were not added to upsert_item function. Issue #11791 - thank you @aalapatirvbd.
  - Fixed error raised when a non string ID is used in an item. It now raises TypeError rather than AttributeError. Issue #11793 - thank you @Rabbit994.




  - Stable release.
  - Added HttpLoggingPolicy to pipeline to enable passing in a custom logger for request and response headers.




  - Fixed bug in synchronized_request for media APIs.
  - Removed MediaReadMode and MediaRequestTimeout from ConnectionPolicy as media requests are not supported.




  - azure.cosmos.errors module deprecated and replaced by azure.cosmos.exceptions
  - The access condition parameters (`access_condition`, `if_match`, `if_none_match`) have been deprecated in favor of separate `match_condition` and `etag` parameters.
  - Fixed bug in routing map provider.
  - Added query Distinct, Offset and Limit support.
  - Default document query execution context now used for
      - ChangeFeed queries
      - single partition queries (partitionkey, partitionKeyRangeId is present in options)
      - Non document queries
  - Errors out for aggregates on multiple partitions, with enable cross partition query set to true, but no "value" keyword present
  - Hits query plan endpoint for other scenarios to fetch query plan
  - Added `__repr__` support for Cosmos entity objects.
  - Updated documentation.




  - Added support for a `timeout` keyword argument to all operations to specify an absolute timeout in seconds
    within which the operation must be completed. If the timeout value is exceeded, a `azure.cosmos.errors.CosmosClientTimeoutError` will be raised.
  - Added a new `ConnectionRetryPolicy` to manage retry behaviour during HTTP connection errors.
  - Added new constructor and per-operation configuration keyword arguments:
      - `retry_total` - Maximum retry attempts.
      - `retry_backoff_max` - Maximum retry wait time in seconds.
      - `retry_fixed_interval` - Fixed retry interval in milliseconds.
      - `retry_read` - Maximum number of socket read retry attempts.
      - `retry_connect` - Maximum number of connection error retry attempts.
      - `retry_status` - Maximum number of retry attempts on error status codes.
      - `retry_on_status_codes` - A list of specific status codes to retry on.
      - `retry_backoff_factor` - Factor to calculate wait time between retry attempts.



  - Added `create_database_if_not_exists()` and `create_container_if_not_exists` functionalities to CosmosClient and Database respectively.



  Version 4.0.0b2 is the second iteration in our efforts to build a more Pythonic client library.

  **Breaking changes**

  - The client connection has been adapted to consume the HTTP pipeline defined in `azure.core.pipeline`.
  - Interactive objects have now been renamed as proxies. This includes:
      - `Database` -> `DatabaseProxy`
      - `User` -> `UserProxy`
      - `Container` -> `ContainerProxy`
      - `Scripts` -> `ScriptsProxy`
  - The constructor of `CosmosClient` has been updated:
      - The `auth` parameter has been renamed to `credential` and will now take an authentication type directly. This means the master key value, a dictionary of resource tokens, or a list of permissions can be passed in. However the old dictionary format is still supported.
      - The `connection_policy` parameter has been made a keyword only parameter, and while it is still supported, each of the individual attributes of the policy can now be passed in as explicit keyword arguments:
          - `request_timeout`
          - `media_request_timeout`
          - `connection_mode`
          - `media_read_mode`
          - `proxy_config`
          - `enable_endpoint_discovery`
          - `preferred_locations`
          - `multiple_write_locations`
  - A new classmethod constructor has been added to `CosmosClient` to enable creation via a connection string retrieved from the Azure portal.
  - Some `read_all` operations have been renamed to `list` operations:
      - `CosmosClient.read_all_databases` -> `CosmosClient.list_databases`
      - `Container.read_all_conflicts` -> `ContainerProxy.list_conflicts`
      - `Database.read_all_containers` -> `DatabaseProxy.list_containers`
      - `Database.read_all_users` -> `DatabaseProxy.list_users`
      - `User.read_all_permissions` -> `UserProxy.list_permissions`
  - All operations that take `request_options` or `feed_options` parameters, these have been moved to keyword only parameters. In addition, while these options dictionaries are still supported, each of the individual options within the dictionary are now supported as explicit keyword arguments.
  - The error hierarchy is now inherited from `azure.core.AzureError` instead of `CosmosError` which has been removed.
      - `HTTPFailure` has been renamed to `CosmosHttpResponseError`
      - `JSONParseFailure` has been removed and replaced by `azure.core.DecodeError`
      - Added additional errors for specific response codes:
          - `CosmosResourceNotFoundError` for status 404
          - `CosmosResourceExistsError` for status 409
          - `CosmosAccessConditionFailedError` for status 412
  - `CosmosClient` can now be run in a context manager to handle closing the client connection.
  - Iterable responses (e.g. query responses and list responses) are now of type `azure.core.paging.ItemPaged`. The method `fetch_next_block` has been replaced by a secondary iterator, accessed by the `by_page` method.



  Version 4.0.0b1 is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Cosmos. For more information about this, and preview releases of other Azure SDK libraries, please visit https://aka.ms/azure-sdk-preview1-python.

  **Breaking changes: New API design**

  - Operations are now scoped to a particular client:
      - `CosmosClient`: This client handles account-level operations. This includes managing service properties and listing the databases within an account.
      - `Database`: This client handles database-level operations. This includes creating and deleting containers, users and stored procedures. It can be accessed from a `CosmosClient` instance by name.
      - `Container`: This client handles operations for a particular container. This includes querying and inserting items and managing properties.
      - `User`: This client handles operations for a particular user. This includes adding and deleting permissions and managing user properties.

      These clients can be accessed by navigating down the client hierarchy using the `get_<child>_client` method. For full details on the new API, please see the [reference documentation](https://aka.ms/azsdk-python-cosmos-ref).
  - Clients are accessed by name rather than by Id. No need to concatenate strings to create links.
  - No more need to import types and methods from individual modules. The public API surface area is available directly in the `azure.cosmos` package.
  - Individual request properties can be provided as keyword arguments rather than constructing a separate `RequestOptions` instance.



  - Added Support for MultiPolygon Datatype
  - Bug Fix in Session Read Retry Policy
  - Bug Fix for Incorrect padding issues while decoding base 64 strings



  - Bug fix in LocationCache
  - Bug fix endpoint retry logic
  - Fixed documentation



  - Multi-region write support added
  - Naming changes
    - DocumentClient to CosmosClient
    - Collection to Container
    - Document to Item
    - Package name updated to "azure-cosmos"
    - Namespace updated to "azure.cosmos"



  - Added support for proxy
  - Added support for reading change feed
  - Added support for collection quota headers
  - Bugfix for large session tokens issue
  - Bugfix for ReadMedia API
  - Bugfix in partition key range cache



  - Added support for default retries on connection issues.



  - Updated documentation to reference Azure Cosmos DB instead of Azure DocumentDB.



  - This SDK version requires the latest version of Azure Cosmos DB Emulator available for download from https://aka.ms/cosmosdb-emulator.



  - bugfix for aggregate dict
  - bugfix for trimming slashes in the resource link
  - tests for unicode encoding



  - Added support for Request Unit per Minute (RU/m) feature.
  - Added support for a new consistency level called ConsistentPrefix.



  - Added support for aggregation queries (COUNT, MIN, MAX, SUM, and AVG).
  - Added an option for disabling SSL verification when running against DocumentDB Emulator.
  - Removed the restriction of dependent requests module to be exactly 2.10.0.
  - Lowered minimum throughput on partitioned collections from 10,100 RU/s to 2500 RU/s.
  - Added support for enabling script logging during stored procedure execution.
  - REST API version bumped to '2017-01-19' with this release.



  - Made editorial changes to documentation comments.



  - Added support for Python 3.5.
  - Added support for connection pooling using the requests module.
  - Added support for session consistency.
  - Added support for TOP/ORDERBY queries for partitioned collections.



  - Added retry policy support for throttled requests. (Throttled requests receive a request rate too large exception, error code 429.)
    By default, DocumentDB retries nine times for each request when error code 429 is encountered, honoring the retryAfter time in the response header.
    A fixed retry interval time can now be set as part of the RetryOptions property on the ConnectionPolicy object if you want to ignore the retryAfter time returned by server between the retries.
    DocumentDB now waits for a maximum of 30 seconds for each request that is being throttled (irrespective of retry count) and returns the response with error code 429.
    This time can also be overridden in the RetryOptions property on ConnectionPolicy object.

  - DocumentDB now returns x-ms-throttle-retry-count and x-ms-throttle-retry-wait-time-ms as the response headers in every request to denote the throttle retry count
    and the cumulative time the request waited between the retries.

  - Removed the RetryPolicy class and the corresponding property (retry_policy) exposed on the document_client class and instead introduced a RetryOptions class
    exposing the RetryOptions property on ConnectionPolicy class that can be used to override some of the default retry options.



  - Added the support for geo-replicated database accounts.
  - Test fixes to move the global host and masterKey into the individual test classes.



  - Added the support for Time To Live(TTL) feature for documents.



  - Bug fixes related to server side partitioning to allow special characters in partitionkey path.



  - Added the support for server side partitioned collections feature.



  - Added Client-side sharding framework to the SDK. Implemented HashPartionResolver and RangePartitionResolver classes.



  - Implement Upsert. New UpsertXXX methods added to support Upsert feature.
  - Implement ID Based Routing. No public API changes, all changes internal.



  - Release skipped to bring version number in alignment with other SDKs



  - Supports GeoSpatial index.
  - Validates id property for all resources. Ids for resources cannot contain ?, /, #, \\, characters or end with a space.
  - Adds new header "index transformation progress" to ResourceResponse.



  - Implements V2 indexing policy



  - Supports proxy connection


pkgId: aef68474514642d0bef70d0a6435ebf40a6b752f6d5de582d8a82c8868cc4831
name: python-azure-cosmos
arch: src
version: 4.9.0
epoch: 0
release: 1
summary: Microsoft Azure Cosmos Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-cosmos-4.9.0-1.src.rpm
checksum_type: sha256
description:
  _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_

  Azure Cosmos DB is a globally distributed, multi-model database service that supports document, key-value, wide-column, and graph databases.

  Use the Azure Cosmos DB SQL API SDK for Python to manage databases and the JSON documents they contain in this NoSQL database service. High level capabilities are:

  * Create Cosmos DB **databases** and modify their settings
  * Create and modify **containers** to store collections of JSON documents
  * Create, read, update, and delete the **items** (JSON documents) in your containers
  * Query the documents in your database using **SQL-like syntax**

  [SDK source code][source_code]
  | [Package (PyPI)][cosmos_pypi]
  | [Package (Conda)](https://anaconda.org/microsoft/azure-cosmos/)
  | [API reference documentation][ref_cosmos_sdk]
  | [Product documentation][cosmos_docs]
  | [Samples][cosmos_samples]

  > This SDK is used for the [SQL API](https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started). For all other APIs, please check the [Azure Cosmos DB documentation](https://docs.microsoft.com/azure/cosmos-db/introduction) to evaluate the best SDK for your project.





  New releases of this SDK won't support Python 2.x starting January 1st, 2022. Please check the [CHANGELOG](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/CHANGELOG.md) for more information.



  * Azure subscription - [Create a free account][azure_sub]
  * Azure [Cosmos DB account][cosmos_account] - SQL API
  * [Python 3.8+][python]

  If you need a Cosmos DB SQL API account, you can create one with this [Azure CLI][azure_cli] command:

  ```Bash
  az cosmosdb create --resource-group <resource-group-name> --name <cosmos-account-name>
  ```



  ```bash
  pip install azure-cosmos
  ```



  Although not required, you can keep your base system and Azure SDK environments isolated from one another if you use a virtual environment. Execute the following commands to configure and then enter a virtual environment with [venv][venv]:

  ```Bash
  python3 -m venv azure-cosmosdb-sdk-environment
  source azure-cosmosdb-sdk-environment/bin/activate
  ```



  Interaction with Cosmos DB starts with an instance of the [CosmosClient][ref_cosmosclient] class. You need an **account**, its **URI**, and one of its **account keys** to instantiate the client object.

  Use the Azure CLI snippet below to populate two environment variables with the database account URI and its primary master key (you can also find these values in the Azure portal). The snippet is formatted for the Bash shell.

  ```Bash
  RES_GROUP=<resource-group-name>
  ACCT_NAME=<cosmos-db-account-name>

  export ACCOUNT_URI=$(az cosmosdb show --resource-group $RES_GROUP --name $ACCT_NAME --query documentEndpoint --output tsv)
  export ACCOUNT_KEY=$(az cosmosdb list-keys --resource-group $RES_GROUP --name $ACCT_NAME --query primaryMasterKey --output tsv)
  ```



  Once you've populated the `ACCOUNT_URI` and `ACCOUNT_KEY` environment variables, you can create the [CosmosClient][ref_cosmosclient].

  ```python
  from azure.cosmos import CosmosClient

  import os
  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  ```



  You can also authenticate a client utilizing your service principal's AAD credentials and the azure identity package.
  You can directly pass in the credentials information to ClientSecretCredential, or use the DefaultAzureCredential:
  ```python
  from azure.cosmos import CosmosClient
  from azure.identity import ClientSecretCredential, DefaultAzureCredential

  import os
  url = os.environ['ACCOUNT_URI']
  tenant_id = os.environ['TENANT_ID']
  client_id = os.environ['CLIENT_ID']
  client_secret = os.environ['CLIENT_SECRET']


  aad_credentials = ClientSecretCredential(
      tenant_id=tenant_id,
      client_id=client_id,
      client_secret=client_secret)


  aad_credentials = DefaultAzureCredential()

  client = CosmosClient(url, aad_credentials)
  ```
  Always ensure that the managed identity you use for AAD authentication has `readMetadata` permissions. <br>
  More information on how to set up AAD authentication: [Set up RBAC for AAD authentication](https://docs.microsoft.com/azure/cosmos-db/how-to-setup-rbac) <br>
  More information on allowed operations for AAD authenticated clients: [RBAC Permission Model](https://aka.ms/cosmos-native-rbac)



  Once you've initialized a [CosmosClient][ref_cosmosclient], you can interact with the primary resource types in Cosmos DB:

  * [Database][ref_database]: A Cosmos DB account can contain multiple databases. When you create a database, you specify the API you'd like to use when interacting with its documents: SQL, MongoDB, Gremlin, Cassandra, or Azure Table. Use the [DatabaseProxy][ref_database] object to manage its containers.

  * [Container][ref_container]: A container is a collection of JSON documents. You create (insert), read, update, and delete items in a container by using methods on the [ContainerProxy][ref_container] object.

  * Item: An Item is the dictionary-like representation of a JSON document stored in a container. Each Item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.

  For more information about these resources, see [Working with Azure Cosmos databases, containers and items][cosmos_resources].




  The keyword-argument `enable_cross_partition_query` accepts 2 options: `None` (default) or `True`.



  When using queries that try to find items based on an **id** value, always make sure you are passing in a string type variable. Azure Cosmos DB only allows string id values and if you use any other datatype, this SDK will return no results and no error messages.



  As of release version 4.3.0b3, if a user does not pass in an explicit consistency level to their client initialization,
  their client will use their database account's default level. Previously, the default was being set to `Session` consistency.
  If for some reason you'd like to keep doing this, you can change your client initialization to include the explicit parameter for this like shown:
  ```python
  from azure.cosmos import CosmosClient

  import os
  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY, consistency_level='Session')
  ```



  Currently, the features below are **not supported**. For alternatives options, check the **Workarounds** section below.



  * Group By queries
  * Queries with COUNT from a DISTINCT subquery: SELECT COUNT (1) FROM (SELECT DISTINCT C.ID FROM C)
  * Direct TCP Mode access
  * Continuation token support for aggregate cross-partition queries like sorting, counting, and distinct.
  Streamable queries like `SELECT * FROM WHERE` *do* support continuation tokens.
  * Change Feed: Processor
  * Change Feed: Read multiple partitions key values
  * Cross-partition ORDER BY for mixed types
  * Enabling diagnostics for async query-type methods



  * Get CollectionSizeUsage, DatabaseUsage, and DocumentUsage metrics
  * Get the connection string
  * Get the minimum RU/s of a container





  Typically, you can use [Azure Portal](https://portal.azure.com/), [Azure Cosmos DB Resource Provider REST API](https://docs.microsoft.com/rest/api/cosmos-db-resource-provider), [Azure CLI](https://docs.microsoft.com/cli/azure/azure-cli-reference-for-cosmos-db) or [PowerShell](https://docs.microsoft.com/azure/cosmos-db/manage-with-powershell) for the control plane unsupported limitations.


  While the SDK supports transactional batch, support for bulk requests is not yet implemented in the Python SDK. You can use the async client along with this [concurrency sample][cosmos_concurrency_sample] we have developed as a reference for a possible workaround.
  >[WARNING]
  > Using the asynchronous client for concurrent operations like shown in this sample will consume a lot of RUs very fast. We **strongly recommend** testing this out against the cosmos emulator first to verify your code works well and avoid incurring charges.





  While the Python language [uses](https://docs.python.org/3/library/stdtypes.html?highlight=boolean#truth-value-testing) "True" and "False" for boolean types, Cosmos DB [accepts](https://docs.microsoft.com/azure/cosmos-db/sql-query-is-bool) "true" and "false" only. In other words, the Python language uses Boolean values with the first uppercase letter and all other lowercase letters, while Cosmos DB and its SQL language use only lowercase letters for those same Boolean values. How to deal with this challenge?

  * Your JSON documents created with Python must use "True" and "False", to pass the language validation. The SDK will convert it to "true" and "false" for you. Meaning that "true" and "false" is what will be stored in Cosmos DB.
  * If you retrieve those documents with the Cosmos DB Portal's Data Explorer, you will see "true" and "false".
  * If you retrieve those documents with this Python SDK, "true" and "false" values will be automatically converted to "True" and "False".



  This SDK uses the [query_items](https://docs.microsoft.com/python/api/azure-cosmos/azure.cosmos.containerproxy?preserve-view=true&view=azure-python#query-items-query--parameters-none--partition-key-none--enable-cross-partition-query-none--max-item-count-none--enable-scan-in-query-none--populate-query-metrics-none----kwargs-) method to submit SQL queries to Azure Cosmos DB.

  Cosmos DB SQL language allows you to [get subitems by using the FROM clause](https://docs.microsoft.com/azure/cosmos-db/sql-query-from#get-subitems-by-using-the-from-clause), to reduce the source to a smaller subset. As an example, you can use `select * from Families.children` instead of `select * from Families`. But please note that:

  * For SQL queries using the `query_items` method, this SDK demands that you specify the `partition_key` or use the `enable_cross_partition_query` flag.
  * If you are getting subitems and specifying the `partition_key`, please make sure that your partition key is included in the subitems, which is not true for most of the cases.



  This is a parameter of the query_items method, an integer indicating the maximum number of items to be returned per page. The `None` value can be specified to let the service determine the optimal item count. This is the recommended configuration value, and the default behavior of this SDK when it is not set.



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

  * [Create a database](#create-a-database "Create a database")
  * [Create a container](#create-a-container "Create a container")
  * [Create an analytical store enabled container](#create-an-analytical-store-enabled-container "Create a container")
  * [Get an existing container](#get-an-existing-container "Get an existing container")
  * [Insert data](#insert-data "Insert data")
  * [Delete data](#delete-data "Delete data")
  * [Query the database](#query-the-database "Query the database")
  * [Get database properties](#get-database-properties "Get database properties")
  * [Get database and container throughputs](#get-database-and-container-throughputs "Get database and container throughputs")
  * [Modify container properties](#modify-container-properties "Modify container properties")
  * [Using the asynchronous client](#using-the-asynchronous-client "Using the asynchronous client")



  After authenticating your [CosmosClient][ref_cosmosclient], you can work with any resource in the account. The code snippet below creates a SQL API database, which is the default when no API is specified when [create_database][ref_cosmosclient_create_database] is invoked.

  ```python
  from azure.cosmos import CosmosClient, exceptions
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  try:
      database = client.create_database(DATABASE_NAME)
  except exceptions.CosmosResourceExistsError:
      database = client.get_database_client(DATABASE_NAME)
  ```



  This example creates a container with default settings. If a container with the same name already exists in the database (generating a `409 Conflict` error), the existing container is obtained instead.

  ```python
  from azure.cosmos import CosmosClient, PartitionKey, exceptions
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'

  try:
      container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"))
  except exceptions.CosmosResourceExistsError:
      container = database.get_container_client(CONTAINER_NAME)
  except exceptions.CosmosHttpResponseError:
      raise
  ```



  This example creates a container with [Analytical Store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction) enabled, for reporting, BI, AI, and Advanced Analytics with [Azure Synapse Link](https://docs.microsoft.com/azure/cosmos-db/synapse-link).

  The options for analytical_storage_ttl are:

  + 0 or Null or not informed: Not enabled.
  + -1: The data will be stored infinitely.
  + Any other number: the actual ttl, in seconds.


  ```python
  CONTAINER_NAME = 'products'
  try:
      container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"),analytical_storage_ttl=-1)
  except exceptions.CosmosResourceExistsError:
      container = database.get_container_client(CONTAINER_NAME)
  except exceptions.CosmosHttpResponseError:
      raise
  ```

  The preceding snippets also handle the [CosmosHttpResponseError][ref_httpfailure] exception if the container creation failed. For more information on error handling and troubleshooting, see the [Troubleshooting](#troubleshooting "Troubleshooting") section.



  Retrieve an existing container from the database:

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)
  ```



  To insert items into a container, pass a dictionary containing your data to [ContainerProxy.upsert_item][ref_container_upsert_item]. Each item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.

  This example inserts several items into the container, each with a unique `id`:

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  for i in range(1, 10):
      container.upsert_item({
              'id': 'item{0}'.format(i),
              'productName': 'Widget',
              'productModel': 'Model {0}'.format(i)
          }
      )
  ```



  To delete items from a container, use [ContainerProxy.delete_item][ref_container_delete_item]. The SQL API in Cosmos DB does not support the SQL `DELETE` statement.

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  for item in container.query_items(
          query='SELECT * FROM products p WHERE p.productModel = "Model 2"',
          enable_cross_partition_query=True):
      container.delete_item(item, partition_key='Widget')
  ```

  > NOTE: If you are using partitioned collection, the value of the `partitionKey` in the example code above, should be set to the value of the partition key for this particular item, not the name of the partition key column in your collection. This holds true for both point reads and deletes.



  A Cosmos DB SQL API database supports querying the items in a container with [ContainerProxy.query_items][ref_container_query_items] using SQL-like syntax.

  This example queries a container for items with a specific `id`:

  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)


  import json
  for item in container.query_items(
          query='SELECT * FROM mycontainer r WHERE r.id="item3"',
          enable_cross_partition_query=True):
      print(json.dumps(item, indent=True))
  ```

  > NOTE: Although you can specify any value for the container name in the `FROM` clause, we recommend you use the container name for consistency.

  Perform parameterized queries by passing a dictionary containing the parameters and their values to [ContainerProxy.query_items][ref_container_query_items]:

  ```python
  discontinued_items = container.query_items(
      query='SELECT * FROM products p WHERE p.productModel = @model',
      parameters=[
          dict(name='@model', value='Model 7')
      ],
      enable_cross_partition_query=True
  )
  for item in discontinued_items:
      print(json.dumps(item, indent=True))
  ```

  For more information on querying Cosmos DB databases using the SQL API, see [Query Azure Cosmos DB data with SQL queries][cosmos_sql_queries].



  Get and display the properties of a database:

  ```python
  from azure.cosmos import CosmosClient
  import os
  import json

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  properties = database.read()
  print(json.dumps(properties))
  ```



  Get and display the throughput values of a database and of a container with dedicated throughput:

  ```python
  from azure.cosmos import CosmosClient
  import os
  import json

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)


  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  db_offer = database.get_throughput()
  print('Found Offer \'{0}\' for Database \'{1}\' and its throughput is \'{2}\''.format(db_offer.properties['id'], database.id, db_offer.properties['content']['offerThroughput']))


  CONTAINER_NAME = 'testContainer'
  container = database.get_container_client(CONTAINER_NAME)
  container_offer = container.get_throughput()
  print('Found Offer \'{0}\' for Container \'{1}\' and its throughput is \'{2}\''.format(container_offer.properties['id'], container.id, container_offer.properties['content']['offerThroughput']))
  ```




  Certain properties of an existing container can be modified. This example sets the default time to live (TTL) for items in the container to 10 seconds:

  ```python
  from azure.cosmos import CosmosClient, PartitionKey
  import os
  import json

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  database.replace_container(
      container,
      partition_key=PartitionKey(path="/productName"),
      default_ttl=10,
  )

  container_props = container.read()
  print(json.dumps(container_props['defaultTtl']))
  ```

  For more information on TTL, see [Time to Live for Azure Cosmos DB data][cosmos_ttl].



  Response headers include metadata information from the executed operations like `etag`, which allows for optimistic concurrency scenarios, or `x-ms-request-charge` which lets you know how many RUs were consumed by the request.
  This applies to all item point operations in both the sync and async clients - and can be used by referencing the `get_response_headers()` method of any response as such:
  ```python
  from azure.cosmos import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  DATABASE_NAME = 'testDatabase'
  CONTAINER_NAME = 'products'
  client = CosmosClient(URL, credential=KEY)
  database = client.get_database_client(DATABASE_NAME)
  container = database.get_container_client(CONTAINER_NAME)

  operation_response = container.create_item({"id": "test_item", "productName": "test_item"})
  operation_headers = operation_response.get_response_headers()
  etag_value = operation_headers['etag']
  request_charge = operation_headers['x-ms-request-charge']
  ```



  The asynchronous cosmos client is a separate client that looks and works in a similar fashion to the existing synchronous client. However, the async client needs to be imported separately and its methods need to be used with the async/await keywords.
  The Async client needs to be initialized and closed after usage, which can be done manually or with the use of a context manager. The example below shows how to do so manually. We don't recommend doing it this way, since it requires that you manually call __aenter__() before using the client.

  ```python
  from azure.cosmos.aio import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  DATABASE_NAME = 'testDatabase'
  CONTAINER_NAME = 'products'

  async def create_products():
      client = CosmosClient(URL, credential=KEY)
      await client.__aenter__() # this piece is important for the SDK to cache account information
      database = client.get_database_client(DATABASE_NAME)
      container = database.get_container_client(CONTAINER_NAME)
      for i in range(10):
          await container.upsert_item({
                  'id': 'item{0}'.format(i),
                  'productName': 'Widget',
                  'productModel': 'Model {0}'.format(i)
              }
          )
      await client.close() # the async client must be closed manually if it's not initialized in a with statement
  ```

  Instead of manually opening and closing the client, it is highly recommended to use the `async with` keywords. This creates a context manager that will initialize and later close the client once you're out of the statement, as well as cache important information the SDK needs. The example below shows how to do so.

  ```python
  from azure.cosmos.aio import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  DATABASE_NAME = 'testDatabase'
  CONTAINER_NAME = 'products'

  async def create_products():
      async with CosmosClient(URL, credential=KEY) as client: # the with statement will automatically initialize and close the async client
          database = client.get_database_client(DATABASE_NAME)
          container = database.get_container_client(CONTAINER_NAME)
          for i in range(10):
              await container.upsert_item({
                      'id': 'item{0}'.format(i),
                      'productName': 'Widget',
                      'productModel': 'Model {0}'.format(i)
                  }
              )
  ```



  Unlike the synchronous client, the async client does not have an `enable_cross_partition` flag in the request. Queries without a specified partition key value will attempt to do a cross partition query by default.

  Query results can be iterated, but the query's raw output returns an asynchronous iterator. This means that each object from the iterator is an awaitable object, and does not yet contain the true query result. In order to obtain the query results you can use an async for loop, which awaits each result as you iterate on the object, or manually await each query result as you iterate over the asynchronous iterator.

  Since the query results are an asynchronous iterator, they can't be cast into lists directly; instead, if you need to create lists from your results, use an async for loop or Python's list comprehension to populate a list:

  ```python
  from azure.cosmos.aio import CosmosClient
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'products'
  container = database.get_container_client(CONTAINER_NAME)

  async def create_lists():
      results = container.query_items(
              query='SELECT * FROM products p WHERE p.productModel = "Model 2"')

      

      item_list = []
      async for item in results:
          item_list.append(item)

      
      item_list = [item async for item in results]
      await client.close()
  ```


  An integrated cache is an in-memory cache that helps you ensure manageable costs and low latency as your request volume grows. The integrated cache has two parts: an item cache for point reads and a query cache for queries. The code snippet below shows you how to use this feature with the point read and query cache methods.

  The benefit of using this is that the point reads and queries that hit the integrated cache won't use any RUs. This means you will have a much lower per-operation cost than reads from the backend.

  [How to configure the Azure Cosmos DB integrated cache (Preview)][cosmos_configure_integrated_cache]

  ```python
  import azure.cosmos.cosmos_client as cosmos_client
  import os

  URL = os.environ['ACCOUNT_URI']
  KEY = os.environ['ACCOUNT_KEY']
  client = cosmos_client.CosmosClient(URL, credential=KEY)
  DATABASE_NAME = 'testDatabase'
  database = client.get_database_client(DATABASE_NAME)
  CONTAINER_NAME = 'testContainer'
  container = database.get_container_client(CONTAINER_NAME)

  def integrated_cache_snippet():
      item_id = body['id']
      query = 'SELECT * FROM c'

      
      container.read_item(item=item_id, partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)

      
      container.query_items(query=query,
           partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)
  ```
  For more information on Integrated Cache, see [Azure Cosmos DB integrated cache - Overview][cosmos_integrated_cache].


  Transactional batch requests allow you to send several operations to be executed at once within the same partition key.
  If all operations succeed in the order they're described within the transactional batch operation, the transaction will be committed.
  However, if any operation fails, the entire transaction is rolled back.

  Transactional batches have a limit of 100 operations per batch, and a total size limit of 1.2Mb for the
  batch operations being passed in.

  Transactional Batch operations look very similar to the singular operations apis, and are tuples containing
  (`operation_type_string`, `args_tuple`, `batch_operation_kwargs_dictionary`), with the kwargs dictionary being optional:
  ```python
  batch_operations = [
          ("create", (item_body,), kwargs),
          ("replace", (item_id, item_body), kwargs),
          ("read", (item_id,), kwargs),
          ("upsert", (item_body,), kwargs),
          ("patch", (item_id, operations), kwargs),
          ("delete", (item_id,), kwargs),
      ]
  batch_results = container.execute_item_batch(batch_operations=batch_operations, partition_key=partition_key)
  ```
  The batch operation kwargs dictionary is limited, and only takes a total of three different key values.
  In the case of wanting to use conditional patching within the batch, the use of `filter_predicate` key is available for the
  patch operation, or in case of wanting to use etags with any of the operations, the use of the `if_match_etag`/`if_none_match_etag`
  keys is available as well.
  ```python
  batch_operations = [
          ("replace", (item_id, item_body), {"if_match_etag": etag}),
          ("patch", (item_id, operations), {"filter_predicate": filter_predicate, "if_none_match_etag": etag}),
      ]
  ```

  We also have some samples showing these transactional batch operations in action with both the [sync][sample_document_mgmt]
  and [async][sample_document_mgmt_async] clients.

  If there is a failure for an operation within the batch, the SDK will raise a `CosmosBatchOperationError` letting you know which operation failed,
  as well as containing the list of failed responses for the failed request.

  For more information on Transactional Batch, see [Azure Cosmos DB Transactional Batch][cosmos_transactional_batch].


  We have added new capabilities to utilize vector embeddings and vector indexing for users to leverage vector
  search utilizing our Cosmos SDK. These two container-level configurations have to be turned on at the account-level
  before you can use them.

  Each vector embedding should have a path to the relevant vector field in your items being stored, a supported data type
  (float32, int8, uint8), the vector's dimensions, and the distance function being used for that embedding. Vectors indexed
  with the flat index type can be at most 505 dimensions. Vectors indexed with the quantizedFlat index type can be at most 4,096 dimensions.
  A sample vector embedding policy would look like this:
  ```python
  vector_embedding_policy = {
      "vectorEmbeddings": [
          {
              "path": "/vector1",
              "dataType": "float32",
              "dimensions": 256,
              "distanceFunction": "euclidean"
          },
          {
              "path": "/vector2",
              "dataType": "int8",
              "dimensions": 200,
              "distanceFunction": "dotproduct"
          },
          {
              "path": "/vector3",
              "dataType": "uint8",
              "dimensions": 400,
              "distanceFunction": "cosine"
          }
      ]
  }
  ```

  Separately, vector indexes have been added to the already existing indexing_policy and only require two fields per index:
  the path to the relevant field to be used, and the type of index from the possible options - flat, quantizedFlat, or diskANN.
  A sample indexing policy with vector indexes would look like this:
  ```python
  indexing_policy = {
          "automatic": True,
          "indexingMode": "consistent",
          "compositeIndexes": [
              [
                  {"path": "/numberField", "order": "ascending"},
                  {"path": "/stringField", "order": "descending"}
              ]
          ],
          "spatialIndexes": [
              {"path": "/location/*", "types": [
                  "Point",
                  "Polygon"]}
          ],
          "vectorIndexes": [
              {"path": "/vector1", "type": "flat"},
              {"path": "/vector2", "type": "quantizedFlat"},
              {"path": "/vector3", "type": "diskANN"}
          ]
      }
  ```

  For vector index types of diskANN and quantizedFlat, there are additional options available as well. These are:

  quantizationByteSize - the number of bytes used in product quantization of the vectors. A larger value may result in better recall for vector searches at the expense of latency. This applies to index types diskANN and quantizedFlat. The allowed range is between 1 and the minimum between 512 and the vector dimensions. The default value is 64.

  indexingSearchListSize - which represents the size of the candidate list of approximate neighbors stored while building the diskANN index as part of the optimization processes. This applies only to index type diskANN. The allowed range is between 25 and 500.
  ```python
  indexing_policy = {
          "automatic": True,
          "indexingMode": "consistent",
          "vectorIndexes": [
              {"path": "/vector1", "type": "quantizedFlat", "quantizationByteSize": 8},
              {"path": "/vector2", "type": "diskANN", "indexingSearchListSize": 50}
          ]
      }
  ```

  You would then pass in the relevant policies to your container creation method to ensure these configurations are used by it.
  The operation will fail if you pass new vector indexes to your indexing policy but forget to pass in an embedding policy.
  ```python
  database.create_container(id=container_id, partition_key=PartitionKey(path="/id"),
                            indexing_policy=indexing_policy, vector_embedding_policy=vector_embedding_policy)
  ```
  ***Note: vector embeddings and vector indexes CANNOT be edited by container replace operations. They are only available directly through creation.***



  With the addition of the vector indexing and vector embedding capabilities, the SDK can now perform order by vector search queries.
  These queries specify the VectorDistance to use as a metric within the query text. These must always use a TOP or LIMIT clause within the query though,
  since vector search queries have to look through a lot of data otherwise and may become too expensive or long-running.
  Since these queries are relatively expensive, the SDK sets a default limit of 50000 max items per query - if you'd like to raise that further, you
  can use the `AZURE_COSMOS_MAX_ITEM_BUFFER_VECTOR_SEARCH` environment variable to do so. However, be advised that queries with too many vector results
  may have additional latencies associated with searching in the service.
  The query syntax for these operations looks like this:
  ```python
  VectorDistance(<embedding1>, <embedding2>, [,<exact_search>], [,<specification>])
  ```
  Embeddings 1 and 2 are the arrays of values for the relevant embeddings, `exact_search` is an optional boolean indicating whether
  to do an exact search vs. an approximate one (default value of false), and `specification` is an optional Json snippet with embedding
  specs that can include `dataType`, `dimensions` and `distanceFunction`. The specifications within the query will take precedence
  to any configurations previously set by a vector embedding policy.
  A sample vector search query would look something like this:
  ```python
      query = "SELECT TOP 10 c.title,VectorDistance(c.embedding, [{}]) AS " \
              "SimilarityScore FROM c ORDER BY VectorDistance(c.embedding, [{}])".format(embeddings_string, embeddings_string)
  ```
  Or if you'd like to add the optional parameters to the vector distance, you could do this:
  ```python
      query = "SELECT TOP 10 c.title,VectorDistance(c.embedding, [{}], true, {{'dataType': 'float32' , 'distanceFunction': 'cosine'}}) AS " \
              "SimilarityScore FROM c ORDER BY VectorDistance(c.embedding, [{}], true, {{'dataType': " \
              "'float32', 'distanceFunction': 'cosine'}})".format(embeddings_string, embeddings_string)
  ```
  The `embeddings_string` above would be your string made from your vector embeddings.
  You can find our sync samples [here][cosmos_index_sample] and our async samples [here][cosmos_index_sample_async] as well to help yourself out.

  *Note: For a limited time, if your query operates against a region or emulator that has not yet been updated the client might run into some issues
  not being able to recognize the new NonStreamingOrderBy capability that makes vector search possible.
  If this happens, you can set the `AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY` environment variable to `"True"` to opt out of this
  functionality and continue operating as usual.*


  We have added new capabilities to utilize full text policies and full text indexing for users to leverage full text search
  utilizing our Cosmos SDK. These two container-level configurations have to be turned on at the account-level
  before you can use them.

  A full text policy allows the user to define the default language to be used for all full text paths, or to set
  a language for each path individually in case the user would like to use full text search on data containing different
  languages in different fields.

  A sample full text policy would look like this:
  ```python
  full_text_policy = {
      "defaultLanguage": "en-US",
      "fullTextPaths": [
          {
              "path": "/text1",
              "language": "en-US"
          },
          {
              "path": "/text2",
              "language": "en-US"
          }
      ]
  }
  ```
  Currently, the only supported language is `en-US` - using the relevant ISO-639 language code to ISO-3166 country code.
  Any non-supported language or code will return an exception when trying to use it - which will also include the list of supported languages.
  This list will include more options in the future; for more information on supported languages, please see [here][cosmos_fts].

  Full text search indexes have been added to the already existing indexing_policy and only require the path to the
  relevant field to be used.
  A sample indexing policy with full text search indexes would look like this:
  ```python
  indexing_policy = {
          "automatic": True,
          "indexingMode": "consistent",
          "compositeIndexes": [
              [
                  {"path": "/numberField", "order": "ascending"},
                  {"path": "/stringField", "order": "descending"}
              ]
          ],
          "fullTextIndexes": [
              {"path": "/abstract"}
          ]
      }
  ```
  Modifying the index in a container is an asynchronous operation that can take a long time to finish. See [here][cosmos_index_policy_change] for more information.
  For more information on using full text policies and full text indexes, see [here][cosmos_fts].



  With the addition of the full text indexing and full text policies, the SDK can now perform full text search and hybrid search queries.
  These queries can utilize the new query functions `FullTextContains()`, `FullTextContainsAll`, and `FullTextContainsAny` to efficiently
  search for the given terms within your item fields.

  Beyond these, you can also utilize the new `Order By RANK` and `Order By RANK RRF` along with `FullTextScore` to execute the [BM25][BM25] scoring algorithm
  or [Reciprocal Rank Fusion][RRF] (RRF) on your query, finding the items with the highest relevance to the terms you are looking for.
  All of these mentioned queries would look something like this:

  - `SELECT TOP 10 c.id, c.text FROM c WHERE FullTextContains(c.text, 'quantum')`


  - `SELECT TOP 10 c.id, c.text FROM c WHERE FullTextContainsAll(c.text, 'quantum', 'theory')`


  - `SELECT TOP 10 c.id, c.text FROM c WHERE FullTextContainsAny(c.text, 'quantum', 'theory')`


  - `SELECT TOP 10 c.id, c.text FROM c ORDER BY RANK FullTextScore(c.text, ['quantum', 'theory'])`


  - `SELECT TOP 10 c.id, c.text FROM c ORDER BY RANK RRF(FullTextScore(c.text, ['quantum', 'theory']), FullTextScore(c.text, ['model']))`


  - `SELECT TOP 10 c.id, c.text FROM c ORDER BY RANK RRF(FullTextScore(c.text, ['quantum', 'theory']), FullTextScore(c.text, ['model']), VectorDistance(c.embedding, {item_embedding}))"`

  These queries must always use a TOP or LIMIT clause within the query since hybrid search queries have to look through a lot of data otherwise and may become too expensive or long-running.
  Since these queries are relatively expensive, the SDK sets a default limit of 1000 max items per query - if you'd like to raise that further, you
  can use the `AZURE_COSMOS_HYBRID_SEARCH_MAX_ITEMS` environment variable to do so. However, be advised that queries with too many vector results
  may have additional latencies associated with searching in the service.

  You can find our sync samples [here][cosmos_index_sample] and our async samples [here][cosmos_index_sample_async] as well for additional guidance.





  When you interact with Cosmos DB using the Python SDK, exceptions returned by the service correspond to the same HTTP status codes returned for REST API requests:

  [HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]

  For example, if you try to create a container using an ID (name) that's already in use in your Cosmos DB database, a `409` error is returned, indicating the conflict. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.

  ```python
  try:
      database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"))
  except exceptions.CosmosResourceExistsError:
      print("""Error creating container
  HTTP status code 409: The ID (name) provided for the container is already in use.
  The container name must be unique within the database.""")

  ```


  This library uses the standard
  [logging](https://docs.python.org/3.5/library/logging.html) library for logging diagnostics.
  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.cosmos import CosmosClient


  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)


  handler = logging.StreamHandler(stream=sys.stdout)
  logger.addHandler(handler)


  client = CosmosClient(URL, credential=KEY, logging_enable=True)
  ```

  Similarly, `logging_enable` can enable detailed logging for a single operation,
  even when it isn't enabled for the client:
  ```python
  database = client.create_database(DATABASE_NAME, logging_enable=True)
  ```
  Alternatively, you can log using the CosmosHttpLoggingPolicy, which extends from the azure core HttpLoggingPolicy, by passing in your logger to the `logger` argument.
  By default, it will use the behaviour from HttpLoggingPolicy. Passing in the `enable_diagnostics_logging` argument will enable the
  CosmosHttpLoggingPolicy, and will have additional information in the response relevant to debugging Cosmos issues.
  ```python
  import logging
  from azure.cosmos import CosmosClient


  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)


  handler = logging.FileHandler(filename="azure")
  logger.addHandler(handler)



  client = CosmosClient(URL, credential=KEY, logger=logger, enable_diagnostics_logging=True)
  ```
  Similarly, logging can be enabled for a single operation by passing in a logger to the singular request.
  However, if you desire to use the CosmosHttpLoggingPolicy to obtain additional information, the `enable_diagnostics_logging` argument needs to be passed in at the client constructor.
  ```python

  client = CosmosClient(URL, credential=KEY, enable_diagnostics_logging=True)
  database = client.create_database(DATABASE_NAME, logger=logger)
  ```


  Azure Core provides the ability for our Python SDKs to use OpenTelemetry with them. The only packages that need to be installed
  to use this functionality are the following:
  ```bash
  pip install azure-core-tracing-opentelemetry
  pip install opentelemetry-sdk
  ```
  For more information on this, we recommend taking a look at this [document](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core-tracing-opentelemetry/README.md)
  from Azure Core describing how to set it up. We have also added a [sample file][telemetry_sample] to show how it can
  be used with our SDK. This works the same way regardless of the Cosmos client you are using.



  For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos DB documentation][cosmos_docs] on docs.microsoft.com.

  <!-- LINKS -->
  [azure_cli]: https://docs.microsoft.com/cli/azure
  [azure_portal]: https://portal.azure.com
  [azure_sub]: https://azure.microsoft.com/free/
  [cloud_shell]: https://docs.microsoft.com/azure/cloud-shell/overview
  [cosmos_account_create]: https://docs.microsoft.com/azure/cosmos-db/how-to-manage-database-account
  [cosmos_account]: https://docs.microsoft.com/azure/cosmos-db/account-overview
  [cosmos_container]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-containers
  [cosmos_database]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-databases
  [cosmos_docs]: https://docs.microsoft.com/azure/cosmos-db/
  [cosmos_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples
  [cosmos_pypi]: https://pypi.org/project/azure-cosmos/
  [cosmos_http_status_codes]: https://docs.microsoft.com/rest/api/cosmos-db/http-status-codes-for-cosmosdb
  [cosmos_item]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-items
  [cosmos_models]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/azure/cosmos/_models.py
  [cosmos_request_units]: https://docs.microsoft.com/azure/cosmos-db/request-units
  [cosmos_resources]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items
  [cosmos_sql_queries]: https://docs.microsoft.com/azure/cosmos-db/how-to-sql-query
  [cosmos_ttl]: https://docs.microsoft.com/azure/cosmos-db/time-to-live
  [cosmos_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/integrated-cache
  [cosmos_configure_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/how-to-configure-integrated-cache
  [python]: https://www.python.org/downloads/
  [ref_container_delete_item]: https://aka.ms/azsdk-python-cosmos-ref-delete-item
  [ref_container_query_items]: https://aka.ms/azsdk-python-cosmos-ref-query-items
  [ref_container_upsert_item]: https://aka.ms/azsdk-python-cosmos-ref-upsert-item
  [ref_container]: https://aka.ms/azsdk-python-cosmos-ref-container
  [ref_cosmos_sdk]: https://aka.ms/azsdk-python-cosmos-ref
  [ref_cosmosclient_create_database]: https://aka.ms/azsdk-python-cosmos-ref-create-database
  [ref_cosmosclient]: https://aka.ms/azsdk-python-cosmos-ref-cosmos-client
  [ref_database]: https://aka.ms/azsdk-python-cosmos-ref-database
  [ref_httpfailure]: https://aka.ms/azsdk-python-cosmos-ref-http-failure
  [sample_database_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/database_management.py
  [sample_document_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management.py
  [sample_document_mgmt_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management_async.py
  [sample_examples_misc]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/examples.py
  [source_code]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos
  [venv]: https://docs.python.org/3/library/venv.html
  [virtualenv]: https://virtualenv.pypa.io
  [telemetry_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/tracing_open_telemetry.py
  [timeouts_document]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/docs/TimeoutAndRetriesConfig.md
  [cosmos_transactional_batch]: https://learn.microsoft.com/azure/cosmos-db/nosql/transactional-batch
  [cosmos_concurrency_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/concurrency_sample.py
  [cosmos_index_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/index_management.py
  [cosmos_index_sample_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/index_management_async.py
  [RRF]: https://learn.microsoft.com/azure/search/hybrid-search-ranking
  [BM25]: https://learn.microsoft.com/azure/search/index-similarity-and-scoring
  [cosmos_fts]: https://aka.ms/cosmosfulltextsearch
  [cosmos_index_policy_change]: https://learn.microsoft.com/azure/cosmos-db/index-policy#modifying-the-indexing-policy



  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.






  * Added full text policy and full text indexing policy. See [PR 37891](https://github.com/Azure/azure-sdk-for-python/pull/37891).
  * Added support for full text search and hybrid search queries. See [PR 38275](https://github.com/Azure/azure-sdk-for-python/pull/38275).


  This version and all future versions will support Python 3.13.


  * Added response headers directly to SDK item point operation responses. See [PR 35791](https://github.com/Azure/azure-sdk-for-python/pull/35791).
  * SDK will now retry all ServiceRequestErrors (failing outgoing requests) before failing. Default number of retries is 3. See [PR 36514](https://github.com/Azure/azure-sdk-for-python/pull/36514).
  * Added Retry Policy for Container Recreate in the Python SDK. See [PR 36043](https://github.com/Azure/azure-sdk-for-python/pull/36043).
  * Added option to disable write payload on writes. See [PR 37365](https://github.com/Azure/azure-sdk-for-python/pull/37365).
  * Added get feed ranges API. See [PR 37687](https://github.com/Azure/azure-sdk-for-python/pull/37687).
  * Added feed range support in `query_items_change_feed`. See [PR 37687](https://github.com/Azure/azure-sdk-for-python/pull/37687).
  * Added **provisional** helper APIs for managing session tokens. See [PR 36971](https://github.com/Azure/azure-sdk-for-python/pull/36971).
  * Added ability to get feed range for a partition key. See [PR 36971](https://github.com/Azure/azure-sdk-for-python/pull/36971).


  * Item-level point operations will now return `CosmosDict` and `CosmosList` response types.
  Responses will still be able to be used directly as previously, but will now have access to their response headers without need for a response hook. See [PR 35791](https://github.com/Azure/azure-sdk-for-python/pull/35791).
  For more information on this, see our README section [here](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/README.md#using-item-operation-response-headers).


  * Consolidated Container Properties Cache to be in the Client to cache partition key definition and container rid to avoid unnecessary container reads. See [PR 35731](https://github.com/Azure/azure-sdk-for-python/pull/35731).
  * Fixed bug with client hangs when running into WriteForbidden exceptions. See [PR 36514](https://github.com/Azure/azure-sdk-for-python/pull/36514).
  * Added retry handling logic for DatabaseAccountNotFound exceptions. See [PR 36514](https://github.com/Azure/azure-sdk-for-python/pull/36514).
  * Fixed SDK regex validation that would not allow for item ids to be longer than 255 characters. See [PR 36569](https://github.com/Azure/azure-sdk-for-python/pull/36569).
  * Fixed issue where 'NoneType' object has no attribute error was raised when a session retry happened during a query. See [PR 37578](https://github.com/Azure/azure-sdk-for-python/pull/37578).
  * Fixed issue where passing subpartition partition key values as a tuple in a query would raise an error. See [PR 38136](https://github.com/Azure/azure-sdk-for-python/pull/38136).
  * Batch requests will now be properly considered as Write operation. See [PR 38365](https://github.com/Azure/azure-sdk-for-python/pull/38365).


  * Getting offer thoughput when it has not been defined in a container will now give a 404/10004 instead of just a 404. See [PR 36043](https://github.com/Azure/azure-sdk-for-python/pull/36043).
  * Incomplete Partition Key Extractions in documents for Subpartitioning now gives 400/1001 instead of just a 400. See [PR 36043](https://github.com/Azure/azure-sdk-for-python/pull/36043).
  * SDK will now make database account calls every 5 minutes to refresh location cache. See [PR 36514](https://github.com/Azure/azure-sdk-for-python/pull/36514).




  * Adds vector embedding policy and vector indexing policy. See [PR 34882](https://github.com/Azure/azure-sdk-for-python/pull/34882).
  * Adds support for vector search non-streaming order by queries. See [PR 35468](https://github.com/Azure/azure-sdk-for-python/pull/35468).
  * Adds support for using the start time option for change feed query API. See [PR 35090](https://github.com/Azure/azure-sdk-for-python/pull/35090).


  * Fixed a bug where change feed query in Async client was not returning all pages due to case-sensitive response headers. See [PR 35090](https://github.com/Azure/azure-sdk-for-python/pull/35090).
  * Fixed a bug when a retryable exception occurs in the first page of a query execution causing query to return 0 results. See [PR 35090](https://github.com/Azure/azure-sdk-for-python/pull/35090).






  * GA release of hierarchical partitioning, index metrics and transactional batch.


  * Keyword arguments were not being passed down for `create_container_if_not_exists()` methods. See [PR 34286](https://github.com/Azure/azure-sdk-for-python/pull/34286).


  * Made several updates to the type hints used throughout the SDK for greater detail. See [PR 33269](https://github.com/Azure/azure-sdk-for-python/pull/33269), [PR 33341](https://github.com/Azure/azure-sdk-for-python/pull/33341), [PR 33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).




  * Fixed bug with async lock not properly releasing on async global endpoint manager. see [PR 34579](https://github.com/Azure/azure-sdk-for-python/pull/34579).


  * Marked `computed_properties` keyword as provisional, un-marked `continuation_token_limit` as provisional. See [PR 34207](https://github.com/Azure/azure-sdk-for-python/pull/34207).


  This version and all future versions will require Python 3.8+.


  * Added **preview** support for Computed Properties on Python SDK (Must be enabled on the account level before it can be used). See [PR 33626](https://github.com/Azure/azure-sdk-for-python/pull/33626).


  * Made use of `response_hook` thread-safe in the sync client. See [PR 33790](https://github.com/Azure/azure-sdk-for-python/pull/33790).
  * Fixed bug with the session container not being properly maintained. See [33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).




  * Added support for capturing Index Metrics in query operations. See [PR 33034](https://github.com/Azure/azure-sdk-for-python/pull/33034).




  * Added support for Transactional Batch. See [PR 32508](https://github.com/Azure/azure-sdk-for-python/pull/32508).
  * Added **preview** support for Priority Based Throttling/Priority Based Execution (Must be enabled at the account level before it can be used). See [PR 32441](https://github.com/Azure/azure-sdk-for-python/pull/32441/).




  * Added support for Hierarchical Partitioning, also known as Subpartitioning. See [PR 31121](https://github.com/Azure/azure-sdk-for-python/pull/31121).


  * Small fix to the `offer_throughput` option in the async client's `create_database_if_not_exists` method, which was previously misspelled as `offerThroughput`.
  See [PR 32076](https://github.com/Azure/azure-sdk-for-python/pull/32076).


  * Marked the outdated `diagnostics.py` file for deprecation since we now recommend the use of our `CosmosHttpLoggingPolicy` for diagnostics.
  For more on the `CosmosHttpLoggingPolicy` see our [README](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#logging-diagnostics).




  * Fixed bug when query with DISTINCT + OFFSET/LIMIT operators returns unexpected result. See [PR 31925](https://github.com/Azure/azure-sdk-for-python/pull/31925).


  * Added additional checks for resource creation using specific characters that cause issues. See [PR 31861](https://github.com/Azure/azure-sdk-for-python/pull/31861).




  * Added support for continuation tokens for streamable cross partition queries. See [PR 31189](https://github.com/Azure/azure-sdk-for-python/pull/31189).


  * Fixed bug with async `create_database_if_not_exists` method not working when passing `offer_throughput` as an option. See [PR 31478](https://github.com/Azure/azure-sdk-for-python/pull/31478).


  * Renamed `response_continuation_token_limit_in_kb` to `continuation_token_limit` for GA. See [PR 31532](https://github.com/Azure/azure-sdk-for-python/pull/31532).




  * Added ability to limit continuation token size when querying for items. See [PR 30731](https://github.com/Azure/azure-sdk-for-python/pull/30731)


  * Fixed bug with async patch_item method. See [PR 30804](https://github.com/Azure/azure-sdk-for-python/pull/30804).




  - GA release of Patch API and Delete All Items By Partition Key




  * Added conditional patching for Patch operations. See [PR 30455](https://github.com/Azure/azure-sdk-for-python/pull/30455).


  * Fixed bug with non english locales causing an error with the RFC 1123 Date Format. See [PR 30125](https://github.com/Azure/azure-sdk-for-python/pull/30125).


  * Refactoring of our client `connection_timeout` and `request_timeout` configurations. See [PR 30171](https://github.com/Azure/azure-sdk-for-python/pull/30171).




   - Added **preview** delete all items by partition key functionality. See [PR 29186](https://github.com/Azure/azure-sdk-for-python/pull/29186). For more information on Partition Key Delete, please see [Azure Cosmos DB Partition Key Delete](https://learn.microsoft.com/azure/cosmos-db/nosql/how-to-delete-by-partition-key?tabs=python-example).
   - Added **preview** partial document update (Patch API) functionality and container methods for patching items with operations. See [PR 29497](https://github.com/Azure/azure-sdk-for-python/pull/29497). For more information on Patch, please see [Azure Cosmos DB Partial Document Update](https://learn.microsoft.com/azure/cosmos-db/partial-document-update).


  * Fixed bug in method `create_container_if_not_exists()` of async database client for unexpected kwargs being passed into `read()` method used internally. See [PR 29136](https://github.com/Azure/azure-sdk-for-python/pull/29136).
  * Fixed bug with method `query_items()` of our async container class, where partition key and cross partition headers would both be set when using partition keys. See [PR 29366](https://github.com/Azure/azure-sdk-for-python/pull/29366/).
  * Fixed bug with client not properly surfacing errors for invalid credentials and identities with insufficient permissions. Users running into 'NoneType has no attribute ConsistencyPolicy' errors when initializing their clients will now see proper authentication exceptions. See [PR 29256](https://github.com/Azure/azure-sdk-for-python/pull/29256).


  * Removed use of `six` package within the SDK.




   - Added `correlated_activity_id` for query operations.
   - Added cross regional retries for Service Unavailable/Request Timeouts for read/Query Plan operations.
   - GA release of CosmosHttpLoggingPolicy and autoscale feature.


  - Bug fix to address queries with VALUE MAX (or any other aggregate) that run into an issue if the query is executed on a container with at least one "empty" partition.




  - GA release of integrated cache functionality. For more information on integrated cache please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache).
  - Added ability to replace analytical ttl on containers. For more information on analytical ttl please see [Azure Cosmos DB analytical store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction).
  - Added `CosmosHttpLoggingPolicy` to replace `HttpLoggingPolicy` for logging HTTP sessions.
  - Added the ability to create containers and databases with autoscale properties for the sync and async clients.
  - Added the ability to update autoscale throughput properties.


  - Fixed parsing of args for overloaded `container.read()` method.
  - Fixed `validate_cache_staleness_value()` method to allow max_integrated_cache_staleness to be an integer greater than or equal to 0.
  - Fixed `__aiter__()` method by removing the async keyword.



  - GA release of Async I/O APIs, including all changes from 4.3.0b1 to 4.3.0b4.


  - Method signatures have been updated to use keyword arguments instead of positional arguments for most method options in the async client.
  - Bugfix: Automatic Id generation for items was turned on for `upsert_items()` method when no 'id' value was present in document body.
  Method call will now require an 'id' field to be present in the document body.


  - Deprecated offer-named methods in favor of their new throughput-named counterparts (`read_offer` -> `get_throughput`).
  - Marked the GetAuthorizationHeader method for deprecation since it will no longer be public in a future release.
  - Added samples showing how to configure retry options for both the sync and async clients.
  - Deprecated the `connection_retry_policy` and `retry_options` options in the sync client.
  - Added user warning to non-query methods trying to use `populate_query_metrics` options.




  - Added support for AAD authentication for the async client.
  - Added support for AAD authentication for the sync client.


  - Changed `_set_partition_key` return typehint in async client.



  >[WARNING]
  >The default `Session` consistency bugfix will impact customers whose database accounts have a `Bounded Staleness` or `Strong`
  > consistency level, and were previously not sending `Session` as a consistency_level parameter when initializing
  > their clients.
  > Default consistency level for the sync and async clients is no longer "Session" and will instead be set to the
    consistency level of the user's cosmos account setting on initialization if not passed during client initialization.
  > Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels)
  > for more details on consistency levels, or the README section on this change [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#note-on-client-consistency-levels).


  - Added new **provisional** `max_integrated_cache_staleness_in_ms` parameter to read item and query items APIs in order
    to make use of the **preview** CosmosDB integrated cache functionality [See PR #22946](https://github.com/Azure/azure-sdk-for-python/pull/22946).
    Please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache) for more details.
  - Added support for split-proof queries for the async client.


  - Default consistency level for the sync and async clients is no longer `Session` and will instead be set to the
    consistency level of the user's cosmos account setting on initialization if not passed during client initialization.
    This change will impact client application in terms of RUs and latency. Users relying on default `Session` consistency
    will need to pass it explicitly if their account consistency is different than `Session`.
    Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels) for more details.
  - Fixed invalid request body being sent when passing in `serverScript` body parameter to replace operations for trigger, sproc and udf resources.
  - Moved `is_system_key` logic in async client.
  - Fixed TypeErrors not being thrown when passing in invalid connection retry policies to the client.



  This version and all future versions will require Python 3.6+. Python 2.7 is no longer supported.
  We will also be removing support for Python 3.6 and will only support Python 3.7+ starting December 2022.


  - Added support for split-proof queries for the sync client.


  - Added async user agent for async client.




  - Added language native async i/o client.



  **Bug fixes**
  - Fixed bug where continuation token is not honored when query_iterable is used to get results by page. Issue #13265.
  - Fixed bug where resource tokens not being honored for document reads and deletes. Issue #13634.

  **New features**
  - Added support for passing partitionKey while querying changefeed. Issue #11689.



  - Added deprecation warning for "lazy" indexing mode. The backend no longer allows creating containers with this mode and will set them to consistent instead.

  **New features**
  - Added the ability to set the analytical storage TTL when creating a new container.

  **Bug fixes**
  - Fixed support for dicts as inputs for get_client APIs.
  - Fixed Python 2/3 compatibility in query iterators.
  - Fixed type hint error. Issue #12570 - thanks @sl-sandy.
  - Fixed bug where options headers were not added to upsert_item function. Issue #11791 - thank you @aalapatirvbd.
  - Fixed error raised when a non string ID is used in an item. It now raises TypeError rather than AttributeError. Issue #11793 - thank you @Rabbit994.




  - Stable release.
  - Added HttpLoggingPolicy to pipeline to enable passing in a custom logger for request and response headers.




  - Fixed bug in synchronized_request for media APIs.
  - Removed MediaReadMode and MediaRequestTimeout from ConnectionPolicy as media requests are not supported.




  - azure.cosmos.errors module deprecated and replaced by azure.cosmos.exceptions
  - The access condition parameters (`access_condition`, `if_match`, `if_none_match`) have been deprecated in favor of separate `match_condition` and `etag` parameters.
  - Fixed bug in routing map provider.
  - Added query Distinct, Offset and Limit support.
  - Default document query execution context now used for
      - ChangeFeed queries
      - single partition queries (partitionkey, partitionKeyRangeId is present in options)
      - Non document queries
  - Errors out for aggregates on multiple partitions, with enable cross partition query set to true, but no "value" keyword present
  - Hits query plan endpoint for other scenarios to fetch query plan
  - Added `__repr__` support for Cosmos entity objects.
  - Updated documentation.




  - Added support for a `timeout` keyword argument to all operations to specify an absolute timeout in seconds
    within which the operation must be completed. If the timeout value is exceeded, a `azure.cosmos.errors.CosmosClientTimeoutError` will be raised.
  - Added a new `ConnectionRetryPolicy` to manage retry behaviour during HTTP connection errors.
  - Added new constructor and per-operation configuration keyword arguments:
      - `retry_total` - Maximum retry attempts.
      - `retry_backoff_max` - Maximum retry wait time in seconds.
      - `retry_fixed_interval` - Fixed retry interval in milliseconds.
      - `retry_read` - Maximum number of socket read retry attempts.
      - `retry_connect` - Maximum number of connection error retry attempts.
      - `retry_status` - Maximum number of retry attempts on error status codes.
      - `retry_on_status_codes` - A list of specific status codes to retry on.
      - `retry_backoff_factor` - Factor to calculate wait time between retry attempts.



  - Added `create_database_if_not_exists()` and `create_container_if_not_exists` functionalities to CosmosClient and Database respectively.



  Version 4.0.0b2 is the second iteration in our efforts to build a more Pythonic client library.

  **Breaking changes**

  - The client connection has been adapted to consume the HTTP pipeline defined in `azure.core.pipeline`.
  - Interactive objects have now been renamed as proxies. This includes:
      - `Database` -> `DatabaseProxy`
      - `User` -> `UserProxy`
      - `Container` -> `ContainerProxy`
      - `Scripts` -> `ScriptsProxy`
  - The constructor of `CosmosClient` has been updated:
      - The `auth` parameter has been renamed to `credential` and will now take an authentication type directly. This means the master key value, a dictionary of resource tokens, or a list of permissions can be passed in. However the old dictionary format is still supported.
      - The `connection_policy` parameter has been made a keyword only parameter, and while it is still supported, each of the individual attributes of the policy can now be passed in as explicit keyword arguments:
          - `request_timeout`
          - `media_request_timeout`
          - `connection_mode`
          - `media_read_mode`
          - `proxy_config`
          - `enable_endpoint_discovery`
          - `preferred_locations`
          - `multiple_write_locations`
  - A new classmethod constructor has been added to `CosmosClient` to enable creation via a connection string retrieved from the Azure portal.
  - Some `read_all` operations have been renamed to `list` operations:
      - `CosmosClient.read_all_databases` -> `CosmosClient.list_databases`
      - `Container.read_all_conflicts` -> `ContainerProxy.list_conflicts`
      - `Database.read_all_containers` -> `DatabaseProxy.list_containers`
      - `Database.read_all_users` -> `DatabaseProxy.list_users`
      - `User.read_all_permissions` -> `UserProxy.list_permissions`
  - All operations that take `request_options` or `feed_options` parameters, these have been moved to keyword only parameters. In addition, while these options dictionaries are still supported, each of the individual options within the dictionary are now supported as explicit keyword arguments.
  - The error hierarchy is now inherited from `azure.core.AzureError` instead of `CosmosError` which has been removed.
      - `HTTPFailure` has been renamed to `CosmosHttpResponseError`
      - `JSONParseFailure` has been removed and replaced by `azure.core.DecodeError`
      - Added additional errors for specific response codes:
          - `CosmosResourceNotFoundError` for status 404
          - `CosmosResourceExistsError` for status 409
          - `CosmosAccessConditionFailedError` for status 412
  - `CosmosClient` can now be run in a context manager to handle closing the client connection.
  - Iterable responses (e.g. query responses and list responses) are now of type `azure.core.paging.ItemPaged`. The method `fetch_next_block` has been replaced by a secondary iterator, accessed by the `by_page` method.



  Version 4.0.0b1 is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Cosmos. For more information about this, and preview releases of other Azure SDK libraries, please visit https://aka.ms/azure-sdk-preview1-python.

  **Breaking changes: New API design**

  - Operations are now scoped to a particular client:
      - `CosmosClient`: This client handles account-level operations. This includes managing service properties and listing the databases within an account.
      - `Database`: This client handles database-level operations. This includes creating and deleting containers, users and stored procedures. It can be accessed from a `CosmosClient` instance by name.
      - `Container`: This client handles operations for a particular container. This includes querying and inserting items and managing properties.
      - `User`: This client handles operations for a particular user. This includes adding and deleting permissions and managing user properties.

      These clients can be accessed by navigating down the client hierarchy using the `get_<child>_client` method. For full details on the new API, please see the [reference documentation](https://aka.ms/azsdk-python-cosmos-ref).
  - Clients are accessed by name rather than by Id. No need to concatenate strings to create links.
  - No more need to import types and methods from individual modules. The public API surface area is available directly in the `azure.cosmos` package.
  - Individual request properties can be provided as keyword arguments rather than constructing a separate `RequestOptions` instance.



  - Added Support for MultiPolygon Datatype
  - Bug Fix in Session Read Retry Policy
  - Bug Fix for Incorrect padding issues while decoding base 64 strings



  - Bug fix in LocationCache
  - Bug fix endpoint retry logic
  - Fixed documentation



  - Multi-region write support added
  - Naming changes
    - DocumentClient to CosmosClient
    - Collection to Container
    - Document to Item
    - Package name updated to "azure-cosmos"
    - Namespace updated to "azure.cosmos"



  - Added support for proxy
  - Added support for reading change feed
  - Added support for collection quota headers
  - Bugfix for large session tokens issue
  - Bugfix for ReadMedia API
  - Bugfix in partition key range cache



  - Added support for default retries on connection issues.



  - Updated documentation to reference Azure Cosmos DB instead of Azure DocumentDB.



  - This SDK version requires the latest version of Azure Cosmos DB Emulator available for download from https://aka.ms/cosmosdb-emulator.



  - bugfix for aggregate dict
  - bugfix for trimming slashes in the resource link
  - tests for unicode encoding



  - Added support for Request Unit per Minute (RU/m) feature.
  - Added support for a new consistency level called ConsistentPrefix.



  - Added support for aggregation queries (COUNT, MIN, MAX, SUM, and AVG).
  - Added an option for disabling SSL verification when running against DocumentDB Emulator.
  - Removed the restriction of dependent requests module to be exactly 2.10.0.
  - Lowered minimum throughput on partitioned collections from 10,100 RU/s to 2500 RU/s.
  - Added support for enabling script logging during stored procedure execution.
  - REST API version bumped to '2017-01-19' with this release.



  - Made editorial changes to documentation comments.



  - Added support for Python 3.5.
  - Added support for connection pooling using the requests module.
  - Added support for session consistency.
  - Added support for TOP/ORDERBY queries for partitioned collections.



  - Added retry policy support for throttled requests. (Throttled requests receive a request rate too large exception, error code 429.)
    By default, DocumentDB retries nine times for each request when error code 429 is encountered, honoring the retryAfter time in the response header.
    A fixed retry interval time can now be set as part of the RetryOptions property on the ConnectionPolicy object if you want to ignore the retryAfter time returned by server between the retries.
    DocumentDB now waits for a maximum of 30 seconds for each request that is being throttled (irrespective of retry count) and returns the response with error code 429.
    This time can also be overridden in the RetryOptions property on ConnectionPolicy object.

  - DocumentDB now returns x-ms-throttle-retry-count and x-ms-throttle-retry-wait-time-ms as the response headers in every request to denote the throttle retry count
    and the cumulative time the request waited between the retries.

  - Removed the RetryPolicy class and the corresponding property (retry_policy) exposed on the document_client class and instead introduced a RetryOptions class
    exposing the RetryOptions property on ConnectionPolicy class that can be used to override some of the default retry options.



  - Added the support for geo-replicated database accounts.
  - Test fixes to move the global host and masterKey into the individual test classes.



  - Added the support for Time To Live(TTL) feature for documents.



  - Bug fixes related to server side partitioning to allow special characters in partitionkey path.



  - Added the support for server side partitioned collections feature.



  - Added Client-side sharding framework to the SDK. Implemented HashPartionResolver and RangePartitionResolver classes.



  - Implement Upsert. New UpsertXXX methods added to support Upsert feature.
  - Implement ID Based Routing. No public API changes, all changes internal.



  - Release skipped to bring version number in alignment with other SDKs



  - Supports GeoSpatial index.
  - Validates id property for all resources. Ids for resources cannot contain ?, /, #, \\, characters or end with a space.
  - Adds new header "index transformation progress" to ResourceResponse.



  - Implements V2 indexing policy



  - Supports proxy connection


pkgId: 215d5c3f1809ec38d194abc334fbc389ddcdb77852f74632b6f4e26f82f649db
name: python-azure-cosmosdb-nspkg
arch: src
version: 2.0.2
epoch: 0
release: 1
summary: Microsoft Azure CosmosDB Namespace Package [Internal]
url: https://github.com/Azure/azure-cosmosdb-python
rpm_license: Apache License 2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-cosmosdb-nspkg-2.0.2-1.src.rpm
checksum_type: sha256
description:
  This is the Microsoft Azure CosmosDB namespace package.
  This package is not intended to be installed directly by the end user.
  It provides the necessary files for other packages to extend the azure.cosmosdb namespace.
  If you are looking to install the Azure CosmosDB libraries, see the
  `azure <https://pypi.python.org/pypi/azure>`__ bundle package.


pkgId: b0eea4add40872ba8830b06aed73feb13d3ac07646668114954e6faee66cc434
name: python-azure-cosmosdb-table
arch: src
version: 1.0.6
epoch: 0
release: 1
summary: Microsoft Azure CosmosDB Table Client Library for Python
url: https://github.com/Azure/azure-cosmosdb-python
rpm_license: Apache License 2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-cosmosdb-table-1.0.6-1.src.rpm
checksum_type: sha256
description:
  This project provides a client library in Python that makes it easy to
  consume Microsoft Azure CosmosDB Table services. For documentation please see
  the Microsoft Azure `Python Developer Center`_ and our `API Reference`_ Page.
      If you are looking for the Service Bus or Azure Management
      libraries, please visit
      https://github.com/Azure/azure-sdk-for-python.


pkgId: 77dc66851cd9363628d14a673db46fa955ef8c5209dd21d5d0a7531baa8e21a4
name: python-azure-data-nspkg
arch: src
version: 1.0.0
epoch: 0
release: 1
summary: Microsoft Azure Data Namespace Package [Internal]
url: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/tables
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-data-nspkg-1.0.0-1.src.rpm
checksum_type: sha256
description:
  This is the Microsoft Azure Data namespace package.

  This package is not intended to be installed directly by the end user.

  It provides the necessary files for other packages to extend the
  azure.data namespace.

  If you are looking to install the Azure Data libraries, see the
  [azure](https://pypi.python.org/pypi/azure) bundle package.


pkgId: d28b30aeaf0ff05f601f17dd14a7a7d11f13c75a629df250b743d154dcba56c2
name: python-azure-data-tables
arch: src
version: 12.5.0
epoch: 0
release: 1
summary: Microsoft Azure Azure Data Tables Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/table/azure-table
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-data-tables-12.5.0-1.src.rpm
checksum_type: sha256
description:
  Azure Tables is a NoSQL data storage service that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS.
  Tables scales as needed to support the amount of data inserted, and allow for the storing of data with non-complex accessing.
  The Azure Tables client can be used to access Azure Storage or Cosmos accounts. This document covers [`azure-data-tables`][Tables_pypi].

  Please note, this package is a replacement for [`azure-cosmosdb-tables`](https://github.com/Azure/azure-cosmos-table-python/tree/master/azure-cosmosdb-table) which is now deprecated. See the [migration guide][migration_guide] for more details.

  [Source code][source_code]
  | [Package (PyPI)][Tables_pypi]
  | [Package (Conda)](https://anaconda.org/microsoft/azure-data-tables/)
  | [API reference documentation][Tables_ref_docs]
  | [Samples][Tables_samples]


  The Azure Tables SDK can access an Azure Storage or CosmosDB account.


  * Python 3.8 or later is required to use this package.
  * You must have an [Azure subscription][azure_subscription] and either
      * an [Azure Storage account][azure_storage_account] or
      * an [Azure Cosmos Account][azure_cosmos_account].


  * To create a new storage account, you can use [Azure Portal][azure_portal_create_account], [Azure PowerShell][azure_powershell_create_account], or [Azure CLI][azure_cli_create_account]:
  * To create a new cosmos storage account, you can use the [Azure CLI][azure_cli_create_cosmos] or [Azure Portal][azure_portal_create_cosmos].


  Install the Azure Tables client library for Python with [pip][pip_link]:
  ```bash
  pip install azure-data-tables
  ```


  The Azure Tables library allows you to interact with two types of resources:
  * the tables in your account
  * the entities within those tables.
  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. The `endpoint` can be found on the page for your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or by running the following Azure CLI command:

  ```bash

  az storage account show -n mystorageaccount -g MyResourceGroup --query "primaryEndpoints.table"
  ```

  Once you have the account URL, it can be used to create the service client:
  ```python
  from azure.data.tables import TableServiceClient
  service = TableServiceClient(endpoint="https://<my_account_name>.table.core.windows.net/", credential=credential)
  ```

  For more information about table service URL's and how to configure custom domain names for Azure Storage check out the [official documentation][azure_portal_account_url]


  The `credential` parameter may be provided in a number of different forms, depending on the type of authorization you wish to use. The Tables library supports the following authorizations:
  * Shared Key
  * Connection String
  * Shared Access Signature Token
  * TokenCredential(AAD)(Supported on Storage)


  To use an account [shared key][azure_shared_key] (aka account key or access key), provide the key as a string. This can be found in your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or by running the following Azure CLI command:

  ```bash
  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
  from azure.core.credentials import AzureNamedKeyCredential

  credential = AzureNamedKeyCredential("my_account_name", "my_access_key")
  with TableServiceClient(
      endpoint="https://<my_account_name>.table.core.windows.net", credential=credential
  ) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  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. If the connection string does not specify a fully qualified endpoint URL (`"TableEndpoint"`), or URL suffix (`"EndpointSuffix"`), the endpoint will be assumed to be an Azure Storage account, and the URL automatically formatted accordingly.

  For Tables Storage, the connection string can be found in your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or with the following Azure CLI command:

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

  For Tables Cosmos, the connection string can be found in your cosmos account in the [Azure Portal][azure_portal_account_url] under the "Connection Strings" section or with the following Azure CLI command:

  ```bash
  az cosmosdb list-connection-strings -g MyResourceGroup -n MyCosmosAccount
  ```

  Create a client from a connection string:

  ```python
  from azure.data.tables import TableServiceClient

  connection_string = "AccountName=<my_account_name>;AccountKey=<my_account_key>;EndpointSuffix=<endpoint_suffix>"
  with TableServiceClient.from_connection_string(conn_str=connection_string) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  To use a [shared access signature (SAS) token][azure_sas_token], 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](https://docs.microsoft.com/rest/api/storageservices/create-service-sas) 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
  from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential

  credential = AzureNamedKeyCredential("my_account_name", "my_access_key")

  sas_token = generate_account_sas(
      credential,
      resource_types=ResourceTypes(service=True),
      permission=AccountSasPermissions(read=True),
      expiry=datetime.utcnow() + timedelta(hours=1),
  )

  with TableServiceClient(
      endpoint="https://<my_account_name>.table.core.windows.net", credential=AzureSasCredential(sas_token)
  ) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  Azure Tables provides integration with Azure Active Directory(Azure AD) for identity-based authentication of requests to the Table service when targeting a Storage endpoint. With Azure AD, you can use role-based access control(RBAC) to grant access to your Azure Table resources to users, groups, or applications.

  To access a table resource with a TokenCredential, the authenticated identity should have either the "Storage Table Data Contributor" or "Storage Table Data Reader" role.

  With the `azure-identity` package, you can seamlessly authorize requests in both development and production environments. To learn more about Azure AD integration in Azure Storage, see the [azure-identity README](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md)

  ```python
  from azure.data.tables import TableServiceClient
  from azure.identity import DefaultAzureCredential

  with TableServiceClient(
      endpoint="https://<my_account_name>.table.core.windows.net", credential=DefaultAzureCredential()
  ) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  Common uses of the Table service included:
  * Storing TBs of structured data capable of serving web scale applications
  * Storing datasets that do not require complex joins, foreign keys, or stored procedures and can be de-normalized for fast access
  * Quickly querying data using a clustered index
  * Accessing data using the OData protocol and LINQ filter expressions

  [comment]: # ( cspell:ignore LINQ )

  The following components make up the Azure 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 Tables client library for Python allows you to interact with each of these components through the
  use of a dedicated client object.


  Two different clients are provided to interact with the various components of the Table Service:
  1. **`TableServiceClient`** -
      * Get and set account setting
      * Query, create, and delete tables within the account.
      * Get a `TableClient` to access a specific table using the `get_table_client` method.
  2. **`TableClient`** -
      * Interacts with a specific table (which need not exist yet).
      * Create, delete, query, and upsert entities within the specified table.
      * Create or delete the specified table itself.


  Entities are similar to rows. An entity has a **`PartitionKey`**, a **`RowKey`**, and a set of properties. A property is a name value pair, similar to a column. Every entity in a table does not need to have the same properties. Entities can be represented as dictionaries like this as an example:
  ```python
  entity = {
      'PartitionKey': 'color',
      'RowKey': 'brand',
      'text': 'Marker',
      'color': 'Purple',
      'price': '5'
  }
  ```
  * **[create_entity][create_entity]** - Add an entity to the table.
  * **[delete_entity][delete_entity]** - Delete an entity from the table.
  * **[update_entity][update_entity]** - Update an entity's information by either merging or replacing the existing entity.
      * `UpdateMode.MERGE` will add new properties to an existing entity it will not delete an existing properties
      * `UpdateMode.REPLACE` will replace the existing entity with the given one, deleting any existing properties not included in the submitted entity
  * **[query_entities][query_entities]** - Query existing entities in a table using [OData filters][odata_syntax].
  * **[get_entity][get_entity]** - Get a specific entity from a table by partition and row key.
  * **[upsert_entity][upsert_entity]** - Merge or replace an entity in a table, or if the entity does not exist, inserts the entity.
      * `UpdateMode.MERGE` will add new properties to an existing entity it will not delete an existing properties
      * `UpdateMode.REPLACE` will replace the existing entity with the given one, deleting any existing properties not included in the submitted entity



  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")



  Create a table in your account and get a `TableClient` to perform operations on the newly created table:

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


  Create entities in the table:

  ```python
  from azure.data.tables import TableServiceClient
  from datetime import datetime

  PRODUCT_ID = u'001234'
  PRODUCT_NAME = u'RedMarker'

  my_entity = {
      u'PartitionKey': PRODUCT_NAME,
      u'RowKey': PRODUCT_ID,
      u'Stock': 15,
      u'Price': 9.99,
      u'Comments': u"great product",
      u'OnSale': True,
      u'ReducedPrice': 7.99,
      u'PurchaseDate': datetime(1973, 10, 4),
      u'BinaryRepresentation': b'product_name'
  }

  table_service_client = TableServiceClient.from_connection_string(conn_str="<connection_string>")
  table_client = table_service_client.get_table_client(table_name="myTable")

  entity = table_client.create_entity(entity=my_entity)
  ```


  Querying entities in the table:

  ```python
  from azure.data.tables import TableClient
  my_filter = "PartitionKey eq 'RedMarker'"
  table_client = TableClient.from_connection_string(conn_str="<connection_string>", table_name="myTable")
  entities = table_client.query_entities(my_filter)
  for entity in entities:
      for key in entity.keys():
          print(f"Key: {key}, Value: {entity[key]}")
  ```


  Optional keyword arguments can be passed in at the client and per-operation level. The azure-core [reference documentation][azure_core_ref_docs] describes available configurations for retries, logging, transport protocols, and more.




  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 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}`





  Azure Tables clients raise exceptions defined in [Azure Core][azure_core_readme].
  When you interact with the Azure table library using the Python SDK, errors returned by the service respond ot the same HTTP status codes for [REST API][tables_rest] requests. The Table service operations will throw a `HttpResponseError` on failure with helpful [error codes][tables_error_codes].

  For examples, if you try to create a table that already exists, a `409` error is returned indicating "Conflict".
  ```python
  from azure.data.tables import TableServiceClient
  from azure.core.exceptions import HttpResponseError
  table_name = 'YourTableName'

  service_client = TableServiceClient.from_connection_string(connection_string)


  tc = service_client.create_table_if_not_exists(table_name)

  try:
      service_client.create_table(table_name)
  except HttpResponseError:
      print(f"Table with name {table_name} already exists")
  ```


  This library uses the standard
  [logging][python_logging] 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

  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)


  handler = logging.StreamHandler(stream=sys.stdout)
  logger.addHandler(handler)


  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 is not enabled for the client:
  ```python
  service_client.create_entity(entity=my_entity, logging_enable=True)
  ```



  Get started with our [Table samples][tables_samples].

  Several Azure 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.


  These code samples show common scenario operations with the Azure Tables client library. The async versions of the samples (the python sample files appended with _async) show asynchronous operations.

  * Create and delete tables: [sample_create_delete_table.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_create_delete_table.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_create_delete_table_async.py))
  * List and query tables: [sample_query_tables.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_query_tables.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_query_tables_async.py))
  * Insert and delete entities: [sample_insert_delete_entities.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_insert_delete_entities_async.py))
  * Query and list entities: [sample_query_table.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_query_table.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/async_samples/sample_query_table_async.py))
  * Update, upsert, and merge entities: [sample_update_upsert_merge_entities.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_update_upsert_merge_entities_async.py))
  * Committing many requests in a single transaction: [sample_batching.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_batching.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_batching_async.py))


  For more extensive documentation on Azure Tables, see the [Azure Tables documentation][Tables_product_doc] on docs.microsoft.com.


  A list of currently known issues relating to Cosmos DB table endpoints can be found [here](https://aka.ms/tablesknownissues).


  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][msft_oss_coc]. For more information see the [Code of Conduct FAQ][msft_oss_coc_faq] or contact [opencode@microsoft.com][contact_msft_oss] with any additional questions or comments.

  <!-- LINKS -->
  [source_code]:https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables
  [Tables_pypi]:https://aka.ms/azsdk/python/tablespypi
  [Tables_ref_docs]:https://docs.microsoft.com/python/api/overview/azure/data-tables-readme?view=azure-python
  [Tables_product_doc]:https://docs.microsoft.com/azure/cosmos-db/table-introduction
  [Tables_samples]:https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples
  [migration_guide]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/migration_guide.md

  [azure_subscription]:https://azure.microsoft.com/free/
  [azure_storage_account]:https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-portal
  [azure_cosmos_account]:https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal
  [pip_link]:https://pypi.org/project/pip/

  [azure_create_cosmos]:https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal
  [azure_cli_create_cosmos]:https://docs.microsoft.com/azure/cosmos-db/scripts/cli/table/create
  [azure_portal_create_cosmos]:https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal
  [azure_portal_create_account]:https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-portal
  [azure_powershell_create_account]:https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-powershell
  [azure_cli_create_account]: https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-cli

  [azure_cli_account_url]:https://docs.microsoft.com/cli/azure/storage/account?view=azure-cli-latest#az-storage-account-show
  [azure_powershell_account_url]:https://docs.microsoft.com/powershell/module/az.storage/get-azstorageaccount?view=azps-4.6.1
  [azure_portal_account_url]:https://docs.microsoft.com/azure/storage/common/storage-account-overview#storage-account-endpoints

  [azure_sas_token]:https://docs.microsoft.com/azure/storage/common/storage-sas-overview
  [azure_shared_key]:https://docs.microsoft.com/rest/api/storageservices/authorize-with-shared-key

  [odata_syntax]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/README.md#writing-filters

  [azure_core_ref_docs]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html
  [azure_core_readme]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md

  [python_logging]: https://docs.python.org/3/library/logging.html
  [tables_error_codes]: https://docs.microsoft.com/rest/api/storageservices/table-service-error-codes

  [msft_oss_coc]:https://opensource.microsoft.com/codeofconduct/
  [msft_oss_coc_faq]:https://opensource.microsoft.com/codeofconduct/faq/
  [contact_msft_oss]:mailto:opencode@microsoft.com

  [tables_rest]: https://docs.microsoft.com/rest/api/storageservices/table-service-rest-api

  [create_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py#L67-L73
  [delete_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py#L89-L92
  [update_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py#L165-L181
  [query_entities]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_query_table.py#L75-L89
  [get_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py#L67-L71
  [upsert_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py#L155-L163

  ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python/sdk/tables/azure-data-tables/README.png)







  * Fixed issue in serializing EntityProperty tuples where a value of None could be serialized as the string "None".


  * Refactored batching code to use latest Core models and improve typing.
  * Added a public type `EntityMetadata`, it is used in `TableEntity`'s metadata.
  * Added support for Python 3.12.
  * Python 3.7 is no longer supported. Please use Python version 3.8 or later.




  * Enabled to specify resource type `container` in account SAS access.


  * Fixed a bug when submitting transactions with an empty operation list. ([#31471](https://github.com/Azure/azure-sdk-for-python/issues/31471))
  * Fixed a bug when decoding response body in string type. Thanks @kldtz for the contribution! ([#31265](https://github.com/Azure/azure-sdk-for-python/pull/31265))
  * Fixed a bug when retrieving an entity with partition key and/or row key in empty string, the empty string values were disappeared in result. ([#31920](https://github.com/Azure/azure-sdk-for-python/issues/31920))


  * Bumped minimum dependency on `azure-core` to `>=1.29.4`. ([#28918](https://github.com/Azure/azure-sdk-for-python/issues/28918) [#31471](https://github.com/Azure/azure-sdk-for-python/issues/31471))




  * Fixed a bug in getting error attribute values when operations failed. ([#27410](https://github.com/Azure/azure-sdk-for-python/issues/27410))


  * Adjusted dependency on `isodate` to `<1.0.0,>=0.6.1`.




  * Fixed a bug when deleting an entity with partition key or row key in empty string.([#24480](https://github.com/Azure/azure-sdk-for-python/issues/24480))


  * Added support for Python 3.11.
  * Dropped `msrest` requirement.
  * Added dependency `isodate` with version range `>=0.6.0`(`isodate` was required by `msrest`).
  * Added dependency `typing-extensions` with version range `>=4.3.0`.




  * Fix handling of client-side exceptions that get raised during service requests (such as [#21416](https://github.com/Azure/azure-sdk-for-python/issues/21416)) ([#24788](https://github.com/Azure/azure-sdk-for-python/pull/24788))


  * Python 3.6 is no longer supported. Please use Python version 3.7 or later.
  * Bumped minimum dependency on `azure-core` to `>=1.24.0`.
  * Bumped minimum dependency on `msrest` to `>=0.7.1`.
  * Added dependency `yarl` with version range `<2.0,>=1.0`.




  * Support for multitenant authentication ([#24278](https://github.com/Azure/azure-sdk-for-python/pull/24278))


  * Fixed bug where odmtype tag was not being included for boolean and int32 types even when a full EdmProperty tuple was passed in. This is needed for CLI compatibility.

  [comment]: # ( cspell:ignore odmtype )




  * Validation of the table name has been removed from the constructor of the TableClient. Instead individual APIs will validate the table name and raise a ValueError only if the service rejects the request due to the table name not being valid (#23106)
  * Fixed hard-coded URL scheme in batch requests (#21953)
  * Improved documentation for query formatting in `query_entities` APIs (#23235)
  * Removed unsecure debug logging


  * Python 2.7 is no longer supported. Please use Python version 3.6 or later.
  * Bumped dependency on `azure-core` to `>=1.15.0`


  **Warning** This release involves a bug fix that may change the behaviour for some users. Partition and Row keys that contain a single quote character (`'`) will now be automatically escaped for upsert, update and delete entity operations. Partition and Row keys that were already escaped, or contained duplicate single quote char (`''`) will now be treated as unescaped values.



  * Resolved bug where strings couldn't be used instead of enum value for entity Update Mode (#20247).
  * Resolved bug where single quote characters in Partition and Row keys were not escaped correctly (#20301).


  * Added support for async iterators in `aio.TableClient.submit_transaction (#21083, thank you yashbhutoria).

  [comment]: # ( cspell:ignore yashbhutoria )


  * Bumped dependency on `msrest` to `>=0.6.21`




  * Storage Accounts only: `TableClient` and `TableServiceClient`s can now use `azure-identity` credentials for authentication. Note: A `TableClient` authenticated with a `TokenCredential` cannot use the `get_table_access_policy` or `set_table_access_policy` methods.


  **Breaking**
  * EdmType.Binary data in entities will now be deserialized as `bytes` in Python 3 and `str` in Python 2, rather than an `EdmProperty` instance. Likewise on serialization, `bytes` in Python 3 and `str` in Python 2 will be interpreted as binary (this is unchanged for Python 3, but breaking for Python 2, where `str` was previously serialized as EdmType.String)
  * `TableClient.create_table` now returns an instance of `TableItem`.
  * All optional parameters for model constructors are now keyword-only.
  * Storage service configuration models have now been prefixed with `Table`, including
    `TableAccessPolicy`, `TableMetrics`, `TableRetentionPolicy`, `TableCorsRule`
  * All parameters for `TableServiceClient.set_service_properties` are now keyword-only.
  * The `credential` parameter for all Clients is now keyword-only.
  * The method `TableClient.get_access_policy` will now return `None` where previously it returned an "empty" access policy object.
  * Timestamp properties on `TableAccessPolicy` instances returned from `TableClient.get_access_policy` will now be deserialized to `datetime` instances.

  **Fixes**
  * Fixed support for Cosmos emulator endpoint, via URL/credential or connection string.
  * Fixed table name from URL parsing in `TableClient.from_table_url` classmethod.
  * The `account_name` attribute on clients will now be pulled from an `AzureNamedKeyCredential` if used.
  * Any additional odata metadata is returned in entity's metadata.
  * The timestamp in entity metadata is now deserialized to a timestamp.
  * If the `prefer` header is added in the `create_entity` operation, the echo will be returned.
  * Errors raised on a 412 if-not-match error will now be a specific `azure.core.exceptions.ResourceModifiedError`.
  * `EdmType.DOUBLE` values are now explicitly typed in the request payload.
  * Fixed de/serialization of list attributes on `TableCorsRule`.


  **Breaking**
  * The `account_url` parameter in the client constructors has been renamed to `endpoint`.
  * The `TableEntity` object now acts exclusively like a dictionary, and no longer supports key access via attributes.
  * Metadata of an entity is now accessed via `TableEntity.metadata` attribute rather than a method.
  * Removed explicit `LinearRetry` and `ExponentialRetry` in favor of keyword parameter.
  * Renamed `filter` parameter in query APIs to `query_filter`.
  * The `location_mode` attribute on clients is now read-only. This has been added as a keyword parameter to the constructor.
  * The `TableItem.table_name` has been renamed to `TableItem.name`.
  * Removed the `TableClient.create_batch` method along with the `TableBatchOperations` object. The transactional batching is now supported via a simple Python list of tuples.
  * `TableClient.send_batch` has been renamed to `TableClient.submit_transaction`.
  * Removed `BatchTransactionResult` object in favor of returning an iterable of batched entities with returned metadata.
  * Removed Batching context-manager behavior
  * `EntityProperty` is now a NampedTuple, and can be represented by a tuple of `(entity, EdmType)`.
  * Renamed `EntityProperty.type` to `EntityProperty.edm_type`.
  * `BatchErrorException` has been renamed to `TableTransactionError`.
  * The `location_mode` is no longer a public attribute on the Clients.
  * The only supported credentials are `AzureNamedKeyCredential`, `AzureSasCredential`, or authentication by connection string
  * Removed `date` and `api_version` from the `TableItem` class.

  **Fixes**
  * Fixed issue with Cosmos merge operations.
  * Removed legacy Storage policies from pipeline.
  * Removed unused legacy client-side encryption attributes from client classes.
  * Fixed sharing of pipeline between service/table clients.
  * Added support for Azurite storage emulator
  * Throws a `RequestTooLargeError` on transaction requests that return a 413 error code
  * Added support for Int64 and Binary types in query filters
  * Added support for `select` keyword parameter to `TableClient.get_entity()`.
  * On `update_entity` and `delete_entity` if no `etag` is supplied via kwargs, the `etag` in the entity will be used if it is in the entity.


  * Updated deserialization of datetime fields in entities to support preservation of the service format with additional decimal place.
  * Passing a string parameter into a query filter will now be escaped to protect against injection.
  * Fixed bug in incrementing retries in async retry policy


  * This version and all future versions will require Python 2.7 or Python 3.6+, Python 3.5 is no longer supported.
  * Adds SAS credential as an authentication option
  * Bumps minimum requirement of `azure-core` to 1.10.0
  * Bumped minimum requirement of msrest from `0.6.10` to `0.6.19`.
  * Adds support for datetime entities with milliseconds
  * Adds support for Shared Access Signature authentication


  * Fixes an [issue](https://github.com/Azure/azure-sdk-for-python/issues/15554) where `query_entities` kwarg `parameters` would not work with multiple parameters or with non-string parameters. This now works with multiple parameters and numeric, string, boolean, UUID, and datetime objects.
  * Fixes an [issue](https://github.com/Azure/azure-sdk-for-python/issues/15653) where `delete_entity` will return a `ClientAuthenticationError` when the '@' symbol is included in the entity.


  * Add support for transactional batching of entity operations.
  * Fixed deserialization bug in `list_tables` and `query_tables` where `TableItem.table_name` was an object instead of a string.
  * Fixed issue where unrecognized entity data fields were silently ignored. They will now raise a `TypeError`.
  * Fixed issue where query filter parameters were being ignored (#15094)


  * Adds support for Enumerable types by converting the Enum to a string before sending to the service


  This is the first beta of the `azure-data-tables` client library. The Azure Tables client library can seamlessly target either Azure Table storage or Azure Cosmos DB table service endpoints with no code changes.


pkgId: 0c6c7a8253f71cc31a4c682fa6cd29b8864d8de04e6d6e2c7fb1b275d3114fab
name: python-azure-data-tables
arch: src
version: 12.6.0
epoch: 0
release: 1
summary: Microsoft Azure Azure Data Tables Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-data-tables-12.6.0-1.src.rpm
checksum_type: sha256
description:
  Azure Tables is a NoSQL data storage service that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS.
  Tables scales as needed to support the amount of data inserted, and allow for the storing of data with non-complex accessing.
  The Azure Tables client can be used to access Azure Storage or Cosmos accounts. This document covers [`azure-data-tables`][Tables_pypi].

  Please note, this package is a replacement for [`azure-cosmosdb-tables`](https://github.com/Azure/azure-cosmos-table-python/tree/master/azure-cosmosdb-table) which is now deprecated. See the [migration guide][migration_guide] for more details.

  [Source code][source_code]
  | [Package (PyPI)][Tables_pypi]
  | [Package (Conda)](https://anaconda.org/microsoft/azure-data-tables/)
  | [API reference documentation][Tables_ref_docs]
  | [Samples][Tables_samples]


  The Azure Tables SDK can access an Azure Storage or CosmosDB account.


  * Python 3.8 or later is required to use this package.
  * You must have an [Azure subscription][azure_subscription] and either
      * an [Azure Storage account][azure_storage_account] or
      * an [Azure Cosmos Account][azure_cosmos_account].


  * To create a new storage account, you can use [Azure Portal][azure_portal_create_account], [Azure PowerShell][azure_powershell_create_account], or [Azure CLI][azure_cli_create_account]:
  * To create a new cosmos storage account, you can use the [Azure CLI][azure_cli_create_cosmos] or [Azure Portal][azure_portal_create_cosmos].


  Install the Azure Tables client library for Python with [pip][pip_link]:
  ```bash
  pip install azure-data-tables
  ```


  The Azure Tables library allows you to interact with two types of resources:
  * the tables in your account
  * the entities within those tables.
  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. The `endpoint` can be found on the page for your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or by running the following Azure CLI command:

  ```bash

  az storage account show -n mystorageaccount -g MyResourceGroup --query "primaryEndpoints.table"
  ```

  Once you have the account URL, it can be used to create the service client:
  ```python
  from azure.data.tables import TableServiceClient
  service = TableServiceClient(endpoint="https://<my_account_name>.table.core.windows.net/", credential=credential)
  ```

  For more information about table service URL's and how to configure custom domain names for Azure Storage check out the [official documentation][azure_portal_account_url]


  The `credential` parameter may be provided in a number of different forms, depending on the type of authorization you wish to use. The Tables library supports the following authorizations:
  * Shared Key
  * Connection String
  * Shared Access Signature Token
  * TokenCredential(AAD)(Supported on Storage)


  To use an account [shared key][azure_shared_key] (aka account key or access key), provide the key as a string. This can be found in your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or by running the following Azure CLI command:

  ```bash
  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
  from azure.core.credentials import AzureNamedKeyCredential

  credential = AzureNamedKeyCredential("my_account_name", "my_access_key")
  with TableServiceClient(
      endpoint="https://<my_account_name>.table.core.windows.net", credential=credential
  ) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  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. If the connection string does not specify a fully qualified endpoint URL (`"TableEndpoint"`), or URL suffix (`"EndpointSuffix"`), the endpoint will be assumed to be an Azure Storage account, and the URL automatically formatted accordingly.

  For Tables Storage, the connection string can be found in your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or with the following Azure CLI command:

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

  For Tables Cosmos, the connection string can be found in your cosmos account in the [Azure Portal][azure_portal_account_url] under the "Connection Strings" section or with the following Azure CLI command:

  ```bash
  az cosmosdb list-connection-strings -g MyResourceGroup -n MyCosmosAccount
  ```

  Create a client from a connection string:

  ```python
  from azure.data.tables import TableServiceClient

  connection_string = "AccountName=<my_account_name>;AccountKey=<my_account_key>;EndpointSuffix=<endpoint_suffix>"
  with TableServiceClient.from_connection_string(conn_str=connection_string) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  To use a [shared access signature (SAS) token][azure_sas_token], 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](https://docs.microsoft.com/rest/api/storageservices/create-service-sas) 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
  from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential

  credential = AzureNamedKeyCredential("my_account_name", "my_access_key")

  sas_token = generate_account_sas(
      credential,
      resource_types=ResourceTypes(service=True),
      permission=AccountSasPermissions(read=True),
      expiry=datetime.utcnow() + timedelta(hours=1),
  )

  with TableServiceClient(
      endpoint="https://<my_account_name>.table.core.windows.net", credential=AzureSasCredential(sas_token)
  ) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  Azure Tables provides integration with Azure Active Directory(Azure AD) for identity-based authentication of requests to the Table service when targeting a Storage endpoint. With Azure AD, you can use role-based access control(RBAC) to grant access to your Azure Table resources to users, groups, or applications.

  To access a table resource with a TokenCredential, the authenticated identity should have either the "Storage Table Data Contributor" or "Storage Table Data Reader" role.

  With the `azure-identity` package, you can seamlessly authorize requests in both development and production environments. To learn more about Azure AD integration in Azure Storage, see the [azure-identity README](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md)

  ```python
  from azure.data.tables import TableServiceClient
  from azure.identity import DefaultAzureCredential

  with TableServiceClient(
      endpoint="https://<my_account_name>.table.core.windows.net", credential=DefaultAzureCredential()
  ) as table_service_client:
      properties = table_service_client.get_service_properties()
      print(f"{properties}")
  ```


  Common uses of the Table service included:
  * Storing TBs of structured data capable of serving web scale applications
  * Storing datasets that do not require complex joins, foreign keys, or stored procedures and can be de-normalized for fast access
  * Quickly querying data using a clustered index
  * Accessing data using the OData protocol and LINQ filter expressions

  [comment]: # ( cspell:ignore LINQ )

  The following components make up the Azure 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 Tables client library for Python allows you to interact with each of these components through the
  use of a dedicated client object.


  Two different clients are provided to interact with the various components of the Table Service:
  1. **`TableServiceClient`** -
      * Get and set account setting
      * Query, create, and delete tables within the account.
      * Get a `TableClient` to access a specific table using the `get_table_client` method.
  2. **`TableClient`** -
      * Interacts with a specific table (which need not exist yet).
      * Create, delete, query, and upsert entities within the specified table.
      * Create or delete the specified table itself.


  Entities are similar to rows. An entity has a **`PartitionKey`**, a **`RowKey`**, and a set of properties. A property is a name value pair, similar to a column. Every entity in a table does not need to have the same properties. Entities can be represented as dictionaries like this as an example:
  ```python
  entity = {
      'PartitionKey': 'color',
      'RowKey': 'brand',
      'text': 'Marker',
      'color': 'Purple',
      'price': '5'
  }
  ```
  * **[create_entity][create_entity]** - Add an entity to the table.
  * **[delete_entity][delete_entity]** - Delete an entity from the table.
  * **[update_entity][update_entity]** - Update an entity's information by either merging or replacing the existing entity.
      * `UpdateMode.MERGE` will add new properties to an existing entity it will not delete an existing properties
      * `UpdateMode.REPLACE` will replace the existing entity with the given one, deleting any existing properties not included in the submitted entity
  * **[query_entities][query_entities]** - Query existing entities in a table using [OData filters][odata_syntax].
  * **[get_entity][get_entity]** - Get a specific entity from a table by partition and row key.
  * **[upsert_entity][upsert_entity]** - Merge or replace an entity in a table, or if the entity does not exist, inserts the entity.
      * `UpdateMode.MERGE` will add new properties to an existing entity it will not delete an existing properties
      * `UpdateMode.REPLACE` will replace the existing entity with the given one, deleting any existing properties not included in the submitted entity



  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")



  Create a table in your account and get a `TableClient` to perform operations on the newly created table:

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


  Create entities in the table:

  ```python
  from azure.data.tables import TableServiceClient
  from datetime import datetime

  PRODUCT_ID = u'001234'
  PRODUCT_NAME = u'RedMarker'

  my_entity = {
      u'PartitionKey': PRODUCT_NAME,
      u'RowKey': PRODUCT_ID,
      u'Stock': 15,
      u'Price': 9.99,
      u'Comments': u"great product",
      u'OnSale': True,
      u'ReducedPrice': 7.99,
      u'PurchaseDate': datetime(1973, 10, 4),
      u'BinaryRepresentation': b'product_name'
  }

  table_service_client = TableServiceClient.from_connection_string(conn_str="<connection_string>")
  table_client = table_service_client.get_table_client(table_name="myTable")

  entity = table_client.create_entity(entity=my_entity)
  ```


  Querying entities in the table:

  ```python
  from azure.data.tables import TableClient
  my_filter = "PartitionKey eq 'RedMarker'"
  table_client = TableClient.from_connection_string(conn_str="<connection_string>", table_name="myTable")
  entities = table_client.query_entities(my_filter)
  for entity in entities:
      for key in entity.keys():
          print(f"Key: {key}, Value: {entity[key]}")
  ```


  Optional keyword arguments can be passed in at the client and per-operation level. The azure-core [reference documentation][azure_core_ref_docs] describes available configurations for retries, logging, transport protocols, and more.




  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 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}`





  Azure Tables clients raise exceptions defined in [Azure Core][azure_core_readme].
  When you interact with the Azure table library using the Python SDK, errors returned by the service respond ot the same HTTP status codes for [REST API][tables_rest] requests. The Table service operations will throw a `HttpResponseError` on failure with helpful [error codes][tables_error_codes].

  For examples, if you try to create a table that already exists, a `409` error is returned indicating "Conflict".
  ```python
  from azure.data.tables import TableServiceClient
  from azure.core.exceptions import HttpResponseError
  table_name = 'YourTableName'

  service_client = TableServiceClient.from_connection_string(connection_string)


  tc = service_client.create_table_if_not_exists(table_name)

  try:
      service_client.create_table(table_name)
  except HttpResponseError:
      print(f"Table with name {table_name} already exists")
  ```


  This library uses the standard
  [logging][python_logging] 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

  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)


  handler = logging.StreamHandler(stream=sys.stdout)
  logger.addHandler(handler)


  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 is not enabled for the client:
  ```python
  service_client.create_entity(entity=my_entity, logging_enable=True)
  ```



  Get started with our [Table samples][tables_samples].

  Several Azure 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.


  These code samples show common scenario operations with the Azure Tables client library. The async versions of the samples (the python sample files appended with _async) show asynchronous operations.

  * Create and delete tables: [sample_create_delete_table.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_create_delete_table.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_create_delete_table_async.py))
  * List and query tables: [sample_query_tables.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_query_tables.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_query_tables_async.py))
  * Insert and delete entities: [sample_insert_delete_entities.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_insert_delete_entities_async.py))
  * Query and list entities: [sample_query_table.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_query_table.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/async_samples/sample_query_table_async.py))
  * Update, upsert, and merge entities: [sample_update_upsert_merge_entities.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_update_upsert_merge_entities_async.py))
  * Committing many requests in a single transaction: [sample_batching.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/sample_batching.py) ([async version](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples/async_samples/sample_batching_async.py))


  For more extensive documentation on Azure Tables, see the [Azure Tables documentation][Tables_product_doc] on docs.microsoft.com.


  A list of currently known issues relating to Cosmos DB table endpoints can be found [here](https://aka.ms/tablesknownissues).


  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][msft_oss_coc]. For more information see the [Code of Conduct FAQ][msft_oss_coc_faq] or contact [opencode@microsoft.com][contact_msft_oss] with any additional questions or comments.

  <!-- LINKS -->
  [source_code]:https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables
  [Tables_pypi]:https://aka.ms/azsdk/python/tablespypi
  [Tables_ref_docs]:https://docs.microsoft.com/python/api/overview/azure/data-tables-readme?view=azure-python
  [Tables_product_doc]:https://docs.microsoft.com/azure/cosmos-db/table-introduction
  [Tables_samples]:https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/tables/azure-data-tables/samples
  [migration_guide]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/migration_guide.md

  [azure_subscription]:https://azure.microsoft.com/free/
  [azure_storage_account]:https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-portal
  [azure_cosmos_account]:https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal
  [pip_link]:https://pypi.org/project/pip/

  [azure_create_cosmos]:https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal
  [azure_cli_create_cosmos]:https://docs.microsoft.com/azure/cosmos-db/scripts/cli/table/create
  [azure_portal_create_cosmos]:https://docs.microsoft.com/azure/cosmos-db/create-cosmosdb-resources-portal
  [azure_portal_create_account]:https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-portal
  [azure_powershell_create_account]:https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-powershell
  [azure_cli_create_account]: https://docs.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-cli

  [azure_cli_account_url]:https://docs.microsoft.com/cli/azure/storage/account?view=azure-cli-latest#az-storage-account-show
  [azure_powershell_account_url]:https://docs.microsoft.com/powershell/module/az.storage/get-azstorageaccount?view=azps-4.6.1
  [azure_portal_account_url]:https://docs.microsoft.com/azure/storage/common/storage-account-overview#storage-account-endpoints

  [azure_sas_token]:https://docs.microsoft.com/azure/storage/common/storage-sas-overview
  [azure_shared_key]:https://docs.microsoft.com/rest/api/storageservices/authorize-with-shared-key

  [odata_syntax]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/README.md#writing-filters

  [azure_core_ref_docs]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html
  [azure_core_readme]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md

  [python_logging]: https://docs.python.org/3/library/logging.html
  [tables_error_codes]: https://docs.microsoft.com/rest/api/storageservices/table-service-error-codes

  [msft_oss_coc]:https://opensource.microsoft.com/codeofconduct/
  [msft_oss_coc_faq]:https://opensource.microsoft.com/codeofconduct/faq/
  [contact_msft_oss]:mailto:opencode@microsoft.com

  [tables_rest]: https://docs.microsoft.com/rest/api/storageservices/table-service-rest-api

  [create_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py#L67-L73
  [delete_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py#L89-L92
  [update_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py#L165-L181
  [query_entities]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_query_table.py#L75-L89
  [get_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py#L67-L71
  [upsert_entity]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/tables/azure-data-tables/samples/sample_update_upsert_merge_entities.py#L155-L163

  ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python/sdk/tables/azure-data-tables/README.png)







  * Added support for Microsoft Entra auth with Azure Cosmos DB for Table's OAuth scope (`https://cosmos.azure.com/.default`).




  * Fixed issue in serializing EntityProperty tuples where a value of None could be serialized as the string "None".


  * Refactored batching code to use latest Core models and improve typing.
  * Added a public type `EntityMetadata`, it is used in `TableEntity`'s metadata.
  * Added support for Python 3.12.
  * Python 3.7 is no longer supported. Please use Python version 3.8 or later.




  * Enabled to specify resource type `container` in account SAS access.


  * Fixed a bug when submitting transactions with an empty operation list. ([#31471](https://github.com/Azure/azure-sdk-for-python/issues/31471))
  * Fixed a bug when decoding response body in string type. Thanks @kldtz for the contribution! ([#31265](https://github.com/Azure/azure-sdk-for-python/pull/31265))
  * Fixed a bug when retrieving an entity with partition key and/or row key in empty string, the empty string values were disappeared in result. ([#31920](https://github.com/Azure/azure-sdk-for-python/issues/31920))


  * Bumped minimum dependency on `azure-core` to `>=1.29.4`. ([#28918](https://github.com/Azure/azure-sdk-for-python/issues/28918) [#31471](https://github.com/Azure/azure-sdk-for-python/issues/31471))




  * Fixed a bug in getting error attribute values when operations failed. ([#27410](https://github.com/Azure/azure-sdk-for-python/issues/27410))


  * Adjusted dependency on `isodate` to `<1.0.0,>=0.6.1`.




  * Fixed a bug when deleting an entity with partition key or row key in empty string.([#24480](https://github.com/Azure/azure-sdk-for-python/issues/24480))


  * Added support for Python 3.11.
  * Dropped `msrest` requirement.
  * Added dependency `isodate` with version range `>=0.6.0`(`isodate` was required by `msrest`).
  * Added dependency `typing-extensions` with version range `>=4.3.0`.




  * Fix handling of client-side exceptions that get raised during service requests (such as [#21416](https://github.com/Azure/azure-sdk-for-python/issues/21416)) ([#24788](https://github.com/Azure/azure-sdk-for-python/pull/24788))


  * Python 3.6 is no longer supported. Please use Python version 3.7 or later.
  * Bumped minimum dependency on `azure-core` to `>=1.24.0`.
  * Bumped minimum dependency on `msrest` to `>=0.7.1`.
  * Added dependency `yarl` with version range `<2.0,>=1.0`.




  * Support for multitenant authentication ([#24278](https://github.com/Azure/azure-sdk-for-python/pull/24278))


  * Fixed bug where odmtype tag was not being included for boolean and int32 types even when a full EdmProperty tuple was passed in. This is needed for CLI compatibility.

  [comment]: # ( cspell:ignore odmtype )




  * Validation of the table name has been removed from the constructor of the TableClient. Instead individual APIs will validate the table name and raise a ValueError only if the service rejects the request due to the table name not being valid (#23106)
  * Fixed hard-coded URL scheme in batch requests (#21953)
  * Improved documentation for query formatting in `query_entities` APIs (#23235)
  * Removed unsecure debug logging


  * Python 2.7 is no longer supported. Please use Python version 3.6 or later.
  * Bumped dependency on `azure-core` to `>=1.15.0`


  **Warning** This release involves a bug fix that may change the behaviour for some users. Partition and Row keys that contain a single quote character (`'`) will now be automatically escaped for upsert, update and delete entity operations. Partition and Row keys that were already escaped, or contained duplicate single quote char (`''`) will now be treated as unescaped values.



  * Resolved bug where strings couldn't be used instead of enum value for entity Update Mode (#20247).
  * Resolved bug where single quote characters in Partition and Row keys were not escaped correctly (#20301).


  * Added support for async iterators in `aio.TableClient.submit_transaction (#21083, thank you yashbhutoria).

  [comment]: # ( cspell:ignore yashbhutoria )


  * Bumped dependency on `msrest` to `>=0.6.21`




  * Storage Accounts only: `TableClient` and `TableServiceClient`s can now use `azure-identity` credentials for authentication. Note: A `TableClient` authenticated with a `TokenCredential` cannot use the `get_table_access_policy` or `set_table_access_policy` methods.


  **Breaking**
  * EdmType.Binary data in entities will now be deserialized as `bytes` in Python 3 and `str` in Python 2, rather than an `EdmProperty` instance. Likewise on serialization, `bytes` in Python 3 and `str` in Python 2 will be interpreted as binary (this is unchanged for Python 3, but breaking for Python 2, where `str` was previously serialized as EdmType.String)
  * `TableClient.create_table` now returns an instance of `TableItem`.
  * All optional parameters for model constructors are now keyword-only.
  * Storage service configuration models have now been prefixed with `Table`, including
    `TableAccessPolicy`, `TableMetrics`, `TableRetentionPolicy`, `TableCorsRule`
  * All parameters for `TableServiceClient.set_service_properties` are now keyword-only.
  * The `credential` parameter for all Clients is now keyword-only.
  * The method `TableClient.get_access_policy` will now return `None` where previously it returned an "empty" access policy object.
  * Timestamp properties on `TableAccessPolicy` instances returned from `TableClient.get_access_policy` will now be deserialized to `datetime` instances.

  **Fixes**
  * Fixed support for Cosmos emulator endpoint, via URL/credential or connection string.
  * Fixed table name from URL parsing in `TableClient.from_table_url` classmethod.
  * The `account_name` attribute on clients will now be pulled from an `AzureNamedKeyCredential` if used.
  * Any additional odata metadata is returned in entity's metadata.
  * The timestamp in entity metadata is now deserialized to a timestamp.
  * If the `prefer` header is added in the `create_entity` operation, the echo will be returned.
  * Errors raised on a 412 if-not-match error will now be a specific `azure.core.exceptions.ResourceModifiedError`.
  * `EdmType.DOUBLE` values are now explicitly typed in the request payload.
  * Fixed de/serialization of list attributes on `TableCorsRule`.


  **Breaking**
  * The `account_url` parameter in the client constructors has been renamed to `endpoint`.
  * The `TableEntity` object now acts exclusively like a dictionary, and no longer supports key access via attributes.
  * Metadata of an entity is now accessed via `TableEntity.metadata` attribute rather than a method.
  * Removed explicit `LinearRetry` and `ExponentialRetry` in favor of keyword parameter.
  * Renamed `filter` parameter in query APIs to `query_filter`.
  * The `location_mode` attribute on clients is now read-only. This has been added as a keyword parameter to the constructor.
  * The `TableItem.table_name` has been renamed to `TableItem.name`.
  * Removed the `TableClient.create_batch` method along with the `TableBatchOperations` object. The transactional batching is now supported via a simple Python list of tuples.
  * `TableClient.send_batch` has been renamed to `TableClient.submit_transaction`.
  * Removed `BatchTransactionResult` object in favor of returning an iterable of batched entities with returned metadata.
  * Removed Batching context-manager behavior
  * `EntityProperty` is now a NampedTuple, and can be represented by a tuple of `(entity, EdmType)`.
  * Renamed `EntityProperty.type` to `EntityProperty.edm_type`.
  * `BatchErrorException` has been renamed to `TableTransactionError`.
  * The `location_mode` is no longer a public attribute on the Clients.
  * The only supported credentials are `AzureNamedKeyCredential`, `AzureSasCredential`, or authentication by connection string
  * Removed `date` and `api_version` from the `TableItem` class.

  **Fixes**
  * Fixed issue with Cosmos merge operations.
  * Removed legacy Storage policies from pipeline.
  * Removed unused legacy client-side encryption attributes from client classes.
  * Fixed sharing of pipeline between service/table clients.
  * Added support for Azurite storage emulator
  * Throws a `RequestTooLargeError` on transaction requests that return a 413 error code
  * Added support for Int64 and Binary types in query filters
  * Added support for `select` keyword parameter to `TableClient.get_entity()`.
  * On `update_entity` and `delete_entity` if no `etag` is supplied via kwargs, the `etag` in the entity will be used if it is in the entity.


  * Updated deserialization of datetime fields in entities to support preservation of the service format with additional decimal place.
  * Passing a string parameter into a query filter will now be escaped to protect against injection.
  * Fixed bug in incrementing retries in async retry policy


  * This version and all future versions will require Python 2.7 or Python 3.6+, Python 3.5 is no longer supported.
  * Adds SAS credential as an authentication option
  * Bumps minimum requirement of `azure-core` to 1.10.0
  * Bumped minimum requirement of msrest from `0.6.10` to `0.6.19`.
  * Adds support for datetime entities with milliseconds
  * Adds support for Shared Access Signature authentication


  * Fixes an [issue](https://github.com/Azure/azure-sdk-for-python/issues/15554) where `query_entities` kwarg `parameters` would not work with multiple parameters or with non-string parameters. This now works with multiple parameters and numeric, string, boolean, UUID, and datetime objects.
  * Fixes an [issue](https://github.com/Azure/azure-sdk-for-python/issues/15653) where `delete_entity` will return a `ClientAuthenticationError` when the '@' symbol is included in the entity.


  * Add support for transactional batching of entity operations.
  * Fixed deserialization bug in `list_tables` and `query_tables` where `TableItem.table_name` was an object instead of a string.
  * Fixed issue where unrecognized entity data fields were silently ignored. They will now raise a `TypeError`.
  * Fixed issue where query filter parameters were being ignored (#15094)


  * Adds support for Enumerable types by converting the Enum to a string before sending to the service


  This is the first beta of the `azure-data-tables` client library. The Azure Tables client library can seamlessly target either Azure Table storage or Azure Cosmos DB table service endpoints with no code changes.


pkgId: a8743850cb5484fa4c0b820c7f60cd9c3dae028e05d22a9fe183be4ef4efadf8
name: python-azure-databricks-api
arch: src
version: 0.6.2
epoch: 0
release: 1
summary: A wrapper for the Azure Databricks REST API
url: http://github.com/ezwiefel/azure-databricks-api
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-databricks-api-0.6.2-1.src.rpm
checksum_type: sha256
description:
  A Python, object-oriented wrapper for the [Azure Databricks REST API 2.0](https://docs.azuredatabricks.net/api/latest/index.html)

  [![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/ezwiefel/azure-databricks-api/Unit%20Tests/main?style=for-the-badge)](https://github.com/ezwiefel/azure-databricks-api/actions?query=workflow%3A%22Unit+Tests%22)
  [![Coveralls github](https://img.shields.io/coveralls/github/ezwiefel/azure-databricks-api?style=for-the-badge)](https://coveralls.io/github/ezwiefel/azure-databricks-api)
  [![PyPI](https://img.shields.io/pypi/v/azure-databricks-api?style=for-the-badge)](https://pypi.org/project/azure-databricks-api/)
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/azure-databricks-api?label=PIP%20DOWNLOADS&style=for-the-badge)](https://pypi.org/project/azure-databricks-api/)
  [![GitHub](https://img.shields.io/github/license/ezwiefel/azure-databricks-api?style=for-the-badge)](https://github.com/ezwiefel/azure-databricks-api/blob/main/LICENSE)


  This package is pip installable.
  ```bash
  pip install azure-databricks-api
  ```


  As of June 25th, 2020 there are 12 different services available in the Azure Databricks API. Currently, the following services are supported by the Azure Databricks API Wrapper.
  * [x] Clusters
  * [ ] Cluster Policies _(Preview)_
  * [x] DBFS
  * [x] Groups _(Must be Databricks admin)_
  * [ ] Instance Pools
  * [ ] Jobs
  * [X] Libraries
  * [ ] MLflow
  * [ ] SCIM _(Preview)_
  * [ ] Secrets
  * [x] Token
  * [x] Workspace



  To create the client object, you pass the Azure region your workspace is located in and the [generated Personal Access Token](https://docs.databricks.com/api/latest/authentication.html#generate-a-token)
  ```python
  from azure_databricks_api import AzureDatabricksRESTClient

  azure_region = '[INSERT YOUR AZURE REGION HERE]'
  token = '[INSERT YOUR PERSONAL ACCESS TOKEN]'

  client = AzureDatabricksRESTClient(region=azure_region, token=token)
  ```


  The services above are implemented as children objects of the client. For example, to pin a cluster, you can either pass the `cluster_name` or `cluster_id` to the `pin()` method:
  ```python
  client.clusters.pin(cluster_name='test_cluster_name')
  ```

  The other services are implemented similarly. (e.g. `client.tokens` or `client.groups`)


pkgId: 145f54b63d36aa5fb0d5b50e943348572774b1d91dbdc084552113a08c0ee757
name: python-azure-datalake-utils
arch: src
version: 0.5.10
epoch: 0
release: 1
summary: Utilidades para interactuar con Azure Datalake.
url: https://github.com/centraal-api/azure-datalake-utils
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-datalake-utils-0.5.10-1.src.rpm
checksum_type: sha256
description:
  [![pypi](https://img.shields.io/pypi/v/azure-datalake-utils.svg)](https://pypi.org/project/azure-datalake-utils/)
  [![python](https://img.shields.io/pypi/pyversions/azure-datalake-utils.svg)](https://pypi.org/project/azure-datalake-utils/)
  [![Build Status](https://github.com/centraal-api/azure-datalake-utils/actions/workflows/dev.yml/badge.svg)](https://github.com/centraal-api/azure-datalake-utils/actions/workflows/dev.yml)
  [![codecov](https://codecov.io/gh/centraal-api/azure-datalake-utils/branch/main/graphs/badge.svg)](https://codecov.io/github/centraal-api/azure-datalake-utils)



  Utilidades para interactuar con Azure Datalake.

  El objetivo es evitar que personas denominadas cientificos ciudadanos tengan que interactuar con librerias, que no son, totalmente relacionadas con el analisis de datos.

  La hipotesis detras de este pensamiento es que se puede lograr incrementar la adopción de estas herramientas si se facilitan y simplifica la interacción de pandas con la lectura del datalake.

  * Documentation: <https://centraal-api.github.io/azure-datalake-utils>
  * GitHub: <https://github.com/centraal-api/azure-datalake-utils>
  * PyPI: <https://pypi.org/project/azure-datalake-utils/>
  * Free software: Apache-2.0




  * Control de autenticación directamente con el Directorio activo de Azure.
  * Lectura de archivos csv, excel, json y parquet de una forma más concisa.
  * Creación de token SAS para generar URL a un path especifico.




  Seguir [checklist del template orginal](https://waynerv.github.io/cookiecutter-pypackage/pypi_release_checklist/).




  La librería es creada y mantenida por [Centraal Studio](https://centraal.studio/).

  Centraal Studio Agredece la alianza con [Haceb](https://www.haceb.com/), cuyos retos internos  de democratizar el acceso a información han motivado la creación de esta librería.

  //

  This package is created and mantained by [Centraal Studio](https://centraal.studio/).

  Centraal Studio appreciate the alliance with [Haceb](https://www.haceb.com/), which internal efforts to democratize the access of company information has motivated the creation of the library.

  This package was created with [Cookiecutter](https://github.com/audreyr/cookiecutter) and the [waynerv/cookiecutter-pypackage](https://github.com/waynerv/cookiecutter-pypackage) project template.


pkgId: 1885e8daed8cff94f9a38a794be6803c6eab851446b93007a8f006af5529a7b2
name: python-azure-debug-relay
arch: src
version: 0.5.1
epoch: 0
release: 1
summary: Azure Debugging Relay: distributed cross-network remote debugging for Python
url: https://pypi.org/project/azure-debug-relay/
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-debug-relay-0.5.1-1.src.rpm
checksum_type: sha256
description:
  Azure Debugging Relay is a [Visual Studio Code](https://code.visualstudio.com/) extension and a Python package for distributed remote debugging. It solves a problem of debugging code running in the cloud and on remote devices,
  simultaneously across multiple nodes and between different networks.

  * [Azure Debugging Relay extension](https://marketplace.visualstudio.com/items?itemName=VladKolesnikov-vladkol.azure-debug-relay) on Visual Studio Marketplace
  * [azure-debug-relay](https://pypi.org/project/azure-debug-relay/) package on PyPI

  Azure Debugging Relay uses [debugpy](https://github.com/microsoft/debugpy) and [Azure Relay](https://docs.microsoft.com/en-us/azure/azure-relay/relay-what-is-it) service to create a debugging tunnel between 2 machines:

  1. Your local Visual Studio Code debugger in `listen` mode.
  1. Your remote code in `attach` mode.

  Both machines can be isolated behind NAT or virtual networks.
  Azure Relay maintains a secure tunnel, just as if these VS Code and a remote process you debug are running in the same `localhost` network.
  Remote components can run in any cloud, local network, with or without public internet access -- all they need is to be able to connect to Azure Relay resource.

  ![Azure Relay Debugging Bridge](https://raw.githubusercontent.com/vladkol/azure-debug-relay/main/images/debug-relay-diagram.png)

  The debugging tunnel is handled by **[Azure Relay Bridge](https://github.com/vladkol/azure-relay-bridge)** utility which is downloaded and installed automatically by Azure Debugging Relay. Azure Relay Bridge can maintain secure TCP and UDP tunnels for different purposes.

  > We currently use a private fork of [Azure Relay Bridge](https://github.com/Azure/azure-relay-bridge) repo.



  * Python 3.6+
  * debugpy 1.2.1+
  * Visual Studio Code 1.34+ (for using VS Code extension)

  Azure Relay Bridge tool is a .NET Core application, so you may need  to install `apt-transport-https` and other .NET Core 3.1 Runtime prerequisites on [Linux](https://docs.microsoft.com/en-us/dotnet/core/install/linux) and [Windows](https://docs.microsoft.com/en-us/dotnet/core/install/windows?tabs=netcore31).

  > You don't have to install .NET Runtime itself - Azure Relay Bridge builds are self-contained.



  * Ubuntu 18+
  * Debian 10+
  * macOS 10+
  * Windows 10



  **On the debugger side (usually your dev machine with Visual Studio code)**:

  > Install [Azure Debugging Relay extension](https://marketplace.visualstudio.com/items?itemName=VladKolesnikov-vladkol.azure-debug-relay) from Visual Studio Marketplace.

  **On the server side**:

  > `python3 -m pip install azure-debug-relay`



  Before you start debugging with Azure Debugging Relay, there are 3 places you configure it:

  1. **Azure Portal or CLI** where you create an Azure Relay resource and an Azure Hybrid Connection in it.
  1. **Local dev machine** where you run Visual Studio Code, its Python extension,
  and Azure Debugging Relay extension with 2 configuration settings.
  1. **Remote machine** where you run the same code files that open locally in VS Code,
  with 2 lines that initiate debugging session for a certain request on an execution flow.



  1. [Create Azure Relay resource](https://ms.portal.azure.com/#create/Microsoft.Relay). Better make one in a region closest to your location.
  1. Once created, switch to the resource, and select `Hybrid Connections` option in the vertical panel.
  1. Add a hybrid connection (`+ Hybrid Connection` button), give it a memorable name (e.g. `test` 🙂) - this is your **Hybrid Connection Name**.
  1. Switch to that new hybrid connection, then select `Shared Access Policies` in the vertical panel.
  1. Add a new policy with `Send` and `Listen` permissions.
  1. Once created, copy its `Primary Connection String`, this is your **Connection String**.



  Choose your name instead of `mydebugrelay1` for an Azure Relay resource, and your custom name for Hybrid Connection instead of `debugrelayhc1`. Same applies to `debugRelayResourceGroup` as resource group.

  ```cmd
  az group create --name debugRelayResourceGroup --location westus2

  az relay namespace create --resource-group debugRelayResourceGroup --name mydebugrelay1 --location westus2

  az relay hyco create --resource-group debugRelayResourceGroup --namespace-name mydebugrelay1 --name debugrelayhc1

  az relay hyco authorization-rule create --resource-group debugRelayResourceGroup --namespace-name mydebugrelay1 --hybrid-connection-name debugrelayhc1 --name sendlisten --rights Send Listen

  az relay hyco authorization-rule keys list --resource-group debugRelayResourceGroup --namespace-name mydebugrelay1 --hybrid-connection-name debugrelayhc1 --name sendlisten
  ```

  Last command will show you something like this:

  ```json
  {
    "keyName": "sendlisten",
    "primaryConnectionString": "Endpoint=sb://mydebugrelay1.servicebus.windows.net/;SharedAccessKeyName=sendlisten;SharedAccessKey=REDACTED1;EntityPath=debugrelayhc1",
    "primaryKey": "REDACTED1",
    "secondaryConnectionString": "Endpoint=sb://mydebugrelay1.servicebus.windows.net/;SharedAccessKeyName=sendlisten;SharedAccessKey=REDACTED2;EntityPath=debugrelayhc1",
    "secondaryKey": "REDACTED2"
  }
  ```

  Use `primaryConnectionString` or `secondaryConnectionString` value as your **Connection String**.

  **Hybrid Connection Name** would be the one you choose instead of `debugrelayhc1`.
  </details>



  Remote Server example (in `samples/simple_demo/remote_server_demo.py`) assumes that Azure Relay credentials will are passes via `.azrelay.json` file in the current directory or via environment variables. Therefore, you have 2 options:

  **Option 1**: Create `.azrelay.json` file in your workspace directory root or whatever directory will be "current",
  and set 2 variables:

  1. `AZRELAY_CONNECTION_STRING` to your **Connection String**.
  1. `AZRELAY_CONNECTION_NAME` to your **Hybrid Connection Name**.

  For example:

  ```json
  {
    "AZRELAY_CONNECTION_STRING": "Endpoint=sb://mydebugrelay1.servicebus.windows.net/;SharedAccessKeyName=sendlisten;SharedAccessKey=REDACTED1;EntityPath=debugrelayhc1",
    "AZRELAY_CONNECTION_NAME": "debugrelayhc1"
  }
  ```

  Make sure you add `.azrelay.json` to `.gitignore` so won't be committed.

  **Option 2**: You can assign these 2 variables as environment variables: `AZRELAY_CONNECTION_STRING` and `AZRELAY_CONNECTION_NAME` instead.



  Use `.azrelay.json` file in the root of your workspace as above or `.vscode/settings.json` with the following settings (actual values are ones you have):

  ```json
  {
    "azure-debug-relay.azrelay-connection-string": "Endpoint=sb://your-relay.servicebus.windows.net/;SharedAccessKeyName=key_name;SharedAccessKey=REDACTED;EntityPath=test",

    "azure-debug-relay.azrelay-connection-name": "test",
  }
  ```

  > Whenever Azure Debugging Relay VS Code extension detects non-empty `azure-debug-relay.hybrid-connection-string` and `azure-debug-relay.hybrid-connection-name` settings (`vscode/settings.json`) or `AZRELAY_CONNECTION_STRING` and `AZRELAY_CONNECTION_NAME` in `.azrelay.json` file, it launches Azure Relay Bridge every time a debugging session with debugpy in `listen` mode is about to begin. If extension settings are not empty and `.azrelay.json` is present, Azure Relay Bridge prefers values from the extension settings (`vscode/settings.json`).

  Visual Studio Code extension ignores `AZRELAY_CONNECTION_STRING` and `AZRELAY_CONNECTION_NAME` environment variables.



  This step must be done on your dev machine in Visual Studio Code before launching the remote code.

  1. Open `remote_server_demo.py` and put a breakpoint in `do_work()` function.
  1. Makes sure your `.vscode/launch.json` has `Python: Listen 5678` configuration as in this repo's `.vscode/launch.json`.
  1. Start debugging in your local Visual Studio Code in `Python: Listen 5678` configuration.

  Notice how the debugger maps paths on the local and the remote machines.
  If your code has a different structure remotely, you may need to provide more sophisticated path mappings. Here is that piece in `.vscode/launch.json`:

  ```json
  "pathMappings": [
      {
          "localRoot": "${workspaceFolder}",
          "remoteRoot": "."
      }
  ]
  ```

  It tells VS Code that the workspace directory locally is mapped to the "current" directory remotely.

  When the debugger looks goes through a file remotely, it needs to find the corresponding file in your local VS Code workspace.
  When debugging `remote_server_demo.py`, the debugger maps `./samples/simple_demo/remote_server_demo.py` remotely to `${workspaceFolder}/samples/simple_demo/remote_server_demo.py` locally.



  1. Clone the repo.
  1. Start `python3 ./samples/simple_demo/remote_server_demo.py --debug=attach`. Notice that current directory must contain `.azrelay.json` file unless configured with environment variables.

  > Terminal session where you start #2 must have the repo's directory as current directory - for a reason of mapping local and remote directories.

  If everything works as it's supposed to, you will hit a breakpoint in your local Visual Studio Code.



  `remote_server_demo.py` shows how you can use Azure Debugging Relay (azure-debug-relay package) with your code.

  **azdebugrelay** module contains DebugRelay class that install and launches Azure Relay Bridge:

  ```python
  from azdebugrelay import DebugRelay, DebugMode, debugpy_connect_with_timeout

  access_key_or_connection_string = "AZURE RELAY HYBRID CONNECTION STRING OR ACCESS KEY"
  relay_connection_name = "HYBRID CONNECTION NAME" # your Hybrid Connection name
  debug_mode = DebugMode.Connect # or DebugMode.WaitForConnection if connecting from another end
  hybrid_connection_url = "HYBRID CONNECTION URL" # can be None if access_key_or_connection_string is a connection string
  host = "127.0.0.1" # local hostname or ip address the debugger starts on
  port = 5678 # any available port that you can use within your machine, may be a list of multiple ports
  debugpy_timeout = 15 # 15 seconds for debugpy to connect

  debug_relay = DebugRelay(access_key_or_connection_string, relay_connection_name, debug_mode, hybrid_connection_url, host, port)
  debug_relay.open()


  debugpy_connect_with_timeout(host, port, debugpy_timeout) # use instead of debugpy.connect









  debug_relay.close()
  ```

  * `access_key_or_connection_string` - SAS Policy key or Connection String for Azure Relay Hybrid Connection. Must have `Send` and `Listen` permissions
  * `relay_connection_name` - name of the Hybrid Connection
  * `debug_mode` - debug connection mode. `DebugMode.WaitForConnection` when starting in listening mode, `DebugMode.Connect` for attaching to a remote debugger.
  * `hybrid_connection_url` - Hybrid Connection URL. Required when access_key_or_connection_string as an access key, otherwise is ignored and may be None.
  * `host` - Local hostname or ip address the debugger starts on, `127.0.0.1` by default
  * `port` - debugging port, `5678` by default

  > We added `debugpy_connect_with_timeout` method on top of **debugpy.connect()**.
  It accepts `connect_timeout_seconds` parameter - how long it should wait for `debugpy.connect()` to connect.
  If the connection is not successfully made within the timeout,
  the debugging session aborts, and that can be handled in your code:
  `debugpy_connect_with_timeout()` returns `True` if the connection was successful, and `False` otherwise.

  Notice that DebugRelay accepts multiple ports to work with (**`ports` parameter is a list**).
  That's because Azure Relay Bridge support forwarding on multiple ports.
  This feature is primarily used by DebugRelay internally
  for [Simultaneous distributed debugging](#simultaneous-distributed-debugging).



  **Simple Azure ML sample** is located in `samples/azure_ml_simple` directory.

  It has 2 components:

  1. `deploy_and_run.py` script that deploys and launches an Azure ML pipeline with a single step.
  2. `steps/train.py` script which contains that simple step.

  Look at the [sample's readme file](samples/azure_ml_simple/README.md).

  **Advanced Azure Machine Learning sample** is located in `samples/azure_ml_advanced`, and demonstrates a complex debugging scenario with parallel steps.

  Look at the [advanced sample's readme file](samples/azure_ml_advanced/README.md).



  You can debug multiple simultaneously running remote nodes using different ports.
  Each execution flow you want to debug must use a separate port - both locally and remotely.

  In Visual Studio code, it is achievable via so called "[compound launch configurations](https://code.visualstudio.com/docs/editor/debugging#_compound-launch-configurations)".
  Compound launch configurations combine multiple launch configurations, and therefore start them at the same time.

  Each launch configuration must be a Python `listen` configuration with a unique name and port:

  ```json
  {
    "name": "Python: Listen 5678",
    "type": "python",
    "request": "attach",
    "listen": {
        "host": "127.0.0.1",
        "port": 5678
    },
    "pathMappings": [
        {
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "."
        }
    ]
  }
  ```

  You need as many launch configurations as number of simultaneous execution flows or nodes you'd like to debug.
  Then you combine them in `.vscode/launch.json` to as a compound:

  ```json
  "compounds": [
    {
      "name": "Python: AML Advanced 3 Listeners",
      "configurations": [
        "Python: Listen 5678",
        "Python: Listen 5679",
        "Python: Listen 5680"
      ]
    }
  ]
  ```

  Remotely, each node you debug should be aware of the port number it should use.
  That port number must be passed to `DebugRelay` object and `debugpy_connect_with_timeout()`.



  Why using [Azure Relay Bridge](https://github.com/Azure/azure-relay-bridge) which is a .NET Core application that we have to install and use via `subprocess` calls?

  Reasons:

  1. Azure Relay has SDKs for .NET, Java, and Node. [No Python SDK or examples](https://github.com/Azure/azure-relay/issues/28#issuecomment-390778193).
  1. Azure Relay Bridge does a lot of things we have to implement otherwise. It is a great tool that can help you connecting different networks for many purposes: for RDP, SSH and other protocols over TCP or UDP.

  A [private fork](https://github.com/vladkol/azure-relay-bridge) we are currently using is only to provide .NET Core 3.1 builds of the most recent code. There is a pending pul-requests: [one](https://github.com/Azure/azure-relay-bridge/pull/22) and [two](https://github.com/Azure/azure-relay-bridge/pull/19).



  > **On macOS, there may be a situation when Azure Relay Bridge (`azbridge`) cannot connect when creating a local forwarder** (`-L` option).

  **Reason**: .NET Core wants you to add your Computer Name to `/etc/hosts` file, and make sure the hostname is configured.

  **Workaround**: Make necessary edits of `/etc/hosts` file, and configure hostname:

  1. Look for your computer's name in `Settings → Sharing`.
  1. Run the following command: `scutil --set HostName "your-computer-name"`. (**replace `your-computer-name` with your computer's name**)
  1. Open `/etc/hosts` in a text editor in *sudo* mode (VS Code can save it later in *sudo* mode).
  1. Add the following line (**replace `your-computer-name` with your computer's name**). Save the file.

  ```text
  127.0.0.1   your-computer-name
  ```

  > **I launched the debugger as described and nothing happened**

  **Reason**: you *probably* didn't put a breakpoint in your VS Code locally. Make sure that breakpoint is in a place that your server process actually runs through.

  > **I do everything right, but nothing works**

  **Reason**: Stop all debugging sessions (if any). Kill all `azbridge` processes locally and remotely. Try again.

  Doesn't help? [File an issue](https://github.com/vladkol/azure-debug-relay/issues/new)! Thank you!


pkgId: ec99a483be7c06b85d4d836ad640bbc99b005c77a46911ce71e227e3f11a9f1e
name: python-azure-developer-loadtesting
arch: src
version: 1.0.0
epoch: 0
release: 1
summary: Microsoft Azure Developer LoadTesting Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-developer-loadtesting-1.0.0-1.src.rpm
checksum_type: sha256
description:
  Azure Load Testing provides client library in python to the user by which they can interact natively with Azure Load Testing service. Azure Load Testing is a fully managed load-testing service that enables you to generate high-scale load. The service simulates traffic for your applications, regardless of where they're hosted. Developers, testers, and quality assurance (QA) engineers can use it to optimize application performance, scalability, or capacity.


  Various documentation is available to help you get started

  <!-- - [Source code][source_code] -->
  - [API reference documentation][api_reference_doc]
  - [Product Documentation][product_documentation]





  ```bash
  python -m pip install azure-developer-loadtesting
  ```



  - Python 3.7 or later is required to use this package.
  - You need an [Azure subscription][azure_sub] to use this package.
  - An existing Azure Developer LoadTesting instance.



  To use an [Azure Active Directory (AAD) token credential][authenticate_with_token],
  provide an instance of the desired credential type obtained from the
  [azure-identity][azure_identity_credentials] library.

  To authenticate with AAD, you must first [pip][pip] install [`azure-identity`][azure_identity_pip]

  After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use.

  As an example, sign in via the Azure CLI `az login` command and [DefaultAzureCredential](https://learn.microsoft.com/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python) will authenticate as that user.

  Use the returned token credential to authenticate the client.



  Azure Developer LoadTesting SDK has 2 sub-clients of the main client (`LoadTestingClient`) to interact with the service, 'administration' and 'test_run'.

  ```python
  from azure.developer.loadtesting import LoadTestAdministrationClient




  from azure.identity import DefaultAzureCredential

  client = LoadTestAdministrationClient(endpoint='<endpoint>', credential=DefaultAzureCredential())
  ```

  `<endpoint>` refers to the data-plane endpoint/URL of the resource.



  The Azure Load Test client library for python allows you to interact with each of these components through the use of clients. There are two top-level clients which are the main entry points for the library

  - `LoadTestAdministrationClient` (`azure.developer.loadtesting.LoadTestAdministrationClient`)
  - `LoadTestRunClient` (`azure.developer.loadtesting.LoadTestRunClient`)

  These two clients also have there asynchronous counterparts, which are
  - `LoadTestAdministrationClient` (`azure.developer.loadtesting.aio.LoadTestAdministrationClient`)
  - `LoadTestRunClient` (`azure.developer.loadtesting.aio.LoadTestRunClient`)



  The `LoadTestAdministrationClient` is used to administer and configure the load tests, app components and metrics.



  A test specifies the test script, and configuration settings for running a load test. You can create one or more tests in an Azure Load Testing resource.



  When you run a load test for an Azure-hosted application, you can monitor resource metrics for the different Azure application components (server-side metrics). While the load test runs, and after completion of the test, you can monitor and analyze the resource metrics in the Azure Load Testing dashboard.



  During a load test, Azure Load Testing collects metrics about the test execution. There are two types of metrics:

  1. Client-side metrics give you details reported by the test engine. These metrics include the number of virtual users, the request response time, the number of failed requests, or the number of requests per second.

  2. Server-side metrics are available for Azure-hosted applications and provide information about your Azure application components. Metrics can be for the number of database reads, the type of HTTP responses, or container resource consumption.



  The `LoadTestRunClient`  is used to start and stop test runs corresponding to a load test. A test run represents one execution of a load test. It collects the logs associated with running the Apache JMeter script, the load test YAML configuration, the list of app components to monitor, and the results of the test.



  Data-plane of Azure Load Testing resources is addressable using the following URL format:

  `00000000-0000-0000-0000-000000000000.aaa.cnt-prod.loadtesting.azure.com`

  The first GUID `00000000-0000-0000-0000-000000000000` is the unique identifier used for accessing the Azure Load Testing resource. This is followed by  `aaa` which is the Azure region of the resource.

  The data-plane endpoint is obtained from Control Plane APIs.

  **Example:** `1234abcd-12ab-12ab-12ab-123456abcdef.eus.cnt-prod.loadtesting.azure.com`

  In the above example, `eus` represents the Azure region `East US`.




  ```python
  from azure.developer.loadtesting import LoadTestAdministrationClient
  from azure.identity import DefaultAzureCredential
  from azure.core.exceptions import HttpResponseError
  import os

  TEST_ID = "some-test-id"
  DISPLAY_NAME = "my-load-test"


  SUBSCRIPTION_ID = os.environ["SUBSCRIPTION_ID"]

  client = LoadTestAdministrationClient(endpoint='<endpoint>', credential=DefaultAzureCredential())

  try:
      result = client.create_or_update_test(
          TEST_ID,
          {
              "description": "",
              "displayName": "My New Load Test",
              "loadTestConfig": {
                  "engineInstances": 1,
                  "splitAllCSVs": False,
              },
              "passFailCriteria": {
                  "passFailMetrics": {
                      "condition1": {
                          "clientmetric": "response_time_ms",
                          "aggregate": "avg",
                          "condition": ">",
                          "value": 300
                      },
                      "condition2": {
                          "clientmetric": "error",
                          "aggregate": "percentage",
                          "condition": ">",
                          "value": 50
                      },
                      "condition3": {
                          "clientmetric": "latency",
                          "aggregate": "avg",
                          "condition": ">",
                          "value": 200,
                          "requestName": "GetCustomerDetails"
                      }
                  }
              },
              "secrets": {
                  "secret1": {
                      "value": "https://sdk-testing-keyvault.vault.azure.net/secrets/sdk-secret",
                      "type": "AKV_SECRET_URI"
                  }
              },
              "environmentVariables": {
                  "my-variable": "value"
              }
          }
      )
      print(result)
  except HttpResponseError as e:
       print('Service responded with error: {}'.format(e.response.json()))

  ```


  ```python
  from azure.developer.loadtesting import LoadTestAdministrationClient
  from azure.identity import DefaultAzureCredential
  from azure.core.exceptions import HttpResponseError

  TEST_ID = "some-test-id"
  FILE_NAME = "some-file-name.jmx"

  client = LoadTestAdministrationClient(endpoint='<endpoint>', credential=DefaultAzureCredential())

  try:

      
      resultPoller = client.begin_upload_test_file(TEST_ID, FILE_NAME, open("sample.jmx", "rb"))

      
      validationResponse = resultPoller.result(600)
      print(validationResponse)

  except HttpResponseError as e:
      print("Failed with error: {}".format(e.response.json()))
  ```


  ```python
  from azure.developer.loadtesting import LoadTestRunClient
  from azure.identity import DefaultAzureCredential
  from azure.core.exceptions import HttpResponseError

  TEST_ID = "some-test-id"
  TEST_RUN_ID = "some-testrun-id"
  DISPLAY_NAME = "my-load-test-run"

  client = LoadTestRunClient(endpoint='<endpoint>', credential=DefaultAzureCredential())

  try:
      testRunPoller = client.begin_test_run(
      TEST_RUN_ID,
          {
              "testId": TEST_ID,
              "displayName": "My New Load Test Run",
          }
      )

      
      result = testRunPoller.result(3600)

      print(result)
  except HttpResponseError as e:
      print("Failed with error: {}".format(e.response.json()))
  ```



  More samples can be found [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/loadtesting/azure-developer-loadtesting/samples).



  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][code_of_conduct]. For more information,
  see the Code of Conduct FAQ or contact opencode@microsoft.com with any
  additional questions or comments.


  More about it is coming soon...

  <!-- LINKS -->
  [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
  [authenticate_with_token]: https://docs.microsoft.com/azure/cognitive-services/authentication?tabs=powershell#authenticate-with-an-authentication-token
  [azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials
  [azure_identity_pip]: https://pypi.org/project/azure-identity/
  [default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential
  [pip]: https://pypi.org/project/pip/
  [azure_sub]: https://azure.microsoft.com/free/
  [api_reference_doc]: https://docs.microsoft.com/rest/api/loadtesting/
  [product_documentation]: https://azure.microsoft.com/services/load-testing/


pkgId: b2345ce8d98dbade0bf7225b979d89f2fe839552056c184266647944324a8de7
name: python-azure-devops-keyring
arch: src
version: 0.3
epoch: 0
release: 1
summary: "(Deprecated) Automatically retrieve passwords for Azure DevOps."
url: https://github.com/Microsoft/azure-devops-keyring
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-devops-keyring-0.3-1.src.rpm
checksum_type: sha256
description:
  **Note:** this package is deprecated in favor of [`artifacts-keyring`](https://pypi.org/project/artifacts-keyring/).


  Provides authentication for [Azure DevOps](https://azure.com/devops) via the `keyring` library

  This is an extension to [keyring](https://pypi.org/project/keyring), and will automatically be loaded.
  Both [pip](https://pypi.org/project/pip) and [twine](https://pypi.org/project/twine) will use `keyring` to
  find credentials.

  To install this package:

  ```
  pip install azure-devops-keyring
  ```

  To use this package through `pip` or `twine`, just provide your repository URL when installing or
  uploading to your Azure Artifacts feed.

  To use this package directly, use `twine.get_credential` and provide your feed URL as the system
  requiring credentials. The username is optional, and the name that should be used will be returned.


pkgId: 99da7cb9c7bd858be64eafed2545b2d22584b62d7a9bc92484e3edec4e6c25a3
name: python-azure-devops-repository-archiver
arch: src
version: 1.6.15
epoch: 0
release: 1
summary: Archive Azure DevOps git repositories to AWS S3
url: https://github.com/stefanfreitag/azure_s3_repository_archiver.git
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-devops-repository-archiver-1.6.15-1.src.rpm
checksum_type: sha256
description:
  The documentation is available [here](https://stefanfreitag.github.io/azure_s3_repository_archiver/).



  * See [CONTRIBUTING.md](CONTRIBUTING.md) for how to contribute to this project.


pkgId: 0ea0a84251b2c532d4af99d17993163373b13d9092557569ccaa9b9e633d547b
name: python-azure-devtools
arch: src
version: 1.2.0
epoch: 0
release: 1
summary: Microsoft Azure Development Tools for SDK
url: https://github.com/Azure/azure-python-devtools
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-devtools-1.2.0-1.src.rpm
checksum_type: sha256
description:
  This package contains tools to aid in developing Python-based Azure code.
  This includes the following components:


pkgId: 99967d7d3ce470b6d4ecd91564c3afa4ebe5dde2162aeaf548b8658c6a41fc36
name: python-azure-digitaltwins-core
arch: src
version: 1.2.0
epoch: 0
release: 1
summary: Microsoft Azure Azure DigitalTwins Core Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/digitaltwins/azure-digitaltwins-core
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-digitaltwins-core-1.2.0-1.src.rpm
checksum_type: sha256
description:
  This package contains an SDK for Azure Digital Twins API to provide access to the Azure Digital Twins service for managing twins, models, relationships, etc.



  _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_





  Azure Digital Twins is a developer platform for next-generation IoT solutions that lets you create, run, and manage digital representations of your business environment, securely and efficiently in the cloud. With Azure Digital Twins, creating live operational state representations is quick and cost-effective, and digital representations stay current with real-time data from IoT and other data sources. If you are new to Azure Digital Twins and would like to learn more about the platform, please make sure you check out the Azure Digital Twins [official documentation page](https://docs.microsoft.com/azure/digital-twins/overview).

  For an introduction on how to program against the Azure Digital Twins service, visit the [coding tutorial page](https://docs.microsoft.com/azure/digital-twins/tutorial-code) for an easy step-by-step guide. Visit [this tutorial](https://docs.microsoft.com/azure/digital-twins/tutorial-command-line-app) to learn how to interact with an Azure Digital Twin instance using a command-line client application. Finally, for a quick guide on how to build an end-to-end Azure Digital Twins solution that is driven by live data from your environment, make sure you check out [this helpful guide](https://docs.microsoft.com/azure/digital-twins/tutorial-end-to-end).

  The guides mentioned above can help you get started with key elements of Azure Digital Twins, such as creating Azure Digital Twins instances, models, twin graphs, etc. Use this samples guide below to familiarize yourself with the various APIs that help you program against Azure Digital Twins.



  Install [azure-digitaltwins-core][pypi_package_keys] and
  [azure-identity][azure_identity_pypi] with [pip][pip]:
  ```Bash
  pip install azure-digitaltwins-core azure-identity
  ```
  [azure-identity][azure_identity] is used for Azure Active Directory
  authentication as demonstrated below.





  To create a new digital twins client, you need the endpoint to an Azure Digital Twin instance and credentials.
  For the samples below, the `AZURE_URL`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` environment variables have to be set.
  The client requires an instance of [TokenCredential](https://docs.microsoft.com/dotnet/api/azure.core.tokencredential?view=azure-dotnet) or [ServiceClientCredentials](https://docs.microsoft.com/dotnet/api/microsoft.rest.serviceclientcredentials?view=azure-dotnet).
  In this samples, we illustrate how to use one derived class: [DefaultAzureCredentials](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet).

  > Note: In order to access the data plane for the Digital Twins service, the entity must be given permissions.
  > To do this, use the Azure CLI command: `az dt rbac assign-role --assignee '<user-email | application-id>' --role owner -n '<your-digital-twins-instance>'`

  DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
  It attempts to use multiple credential types in an order until it finds a working credential.



  ```python Snippet:dt_create_digitaltwins_service_client.py




  url = os.getenv("AZURE_URL")





  credential = DefaultAzureCredential()
  service_client = DigitalTwinsClient(url, credential)
  ```



  Azure Digital Twins is an Azure IoT service that creates comprehensive models of the physical environment. It can create spatial intelligence graphs to model the relationships and interactions between people, spaces, and devices.
  You can learn more about Azure Digital Twins by visiting [Azure Digital Twins Documentation](https://docs.microsoft.com/azure/digital-twins/).



  You can explore the digital twins APIs (using the client library) using the samples project.

  The samples project demonstrates the following:

  - Instantiate the client
  - Create, get, and decommission models
  - Create, query, and delete a digital twin
  - Get and update components for a digital twin
  - Create, get, and delete relationships between digital twins
  - Create, get, and delete event routes for digital twin
  - Publish telemetry messages to a digital twin and digital twin component





  Let's create models using the code below. You need to pass an array containing list of models.

  ```Python Snippet:dt_models_lifecycle
  temporary_component = {
      "@id": component_id,
      "@type": "Interface",
      "@context": "dtmi:dtdl:context;2",
      "displayName": "Component1",
      "contents": [
      {
          "@type": "Property",
          "name": "ComponentProp1",
          "schema": "string"
      },
      {
          "@type": "Telemetry",
          "name": "ComponentTelemetry1",
          "schema": "integer"
      }
      ]
  }

  temporary_model = {
      "@id": model_id,
      "@type": "Interface",
      "@context": "dtmi:dtdl:context;2",
      "displayName": "TempModel",
      "contents": [
      {
          "@type": "Property",
          "name": "Prop1",
          "schema": "string"
      },
      {
          "@type": "Component",
          "name": "Component1",
          "schema": component_id
      },
      {
          "@type": "Telemetry",
          "name": "Telemetry1",
          "schema": "integer"
      }
      ]
  }

  new_models = [temporary_component, temporary_model]
  models = service_client.create_models(new_models)
  print('Created Models:')
  print(models)
  ```


  Using `list_models` to retrieve all created models

  ```Python Snippet:dt_models_lifecycle
  listed_models = service_client.list_models()
  for model in listed_models:
      print(model)
  ```


  Use `get_model` with model's unique identifier to get a specific model.

  ```Python Snippet:dt_models_lifecycle

  get_model = service_client.get_model(model_id)
  print('Get Model:')
  print(get_model)
  ```


  To decommision a model, pass in a model Id for the model you want to decommision.

  ```Python Snippet:dt_models_lifecycle

  service_client.decommission_model(model_id)
  ```


  To delete a model, pass in a model Id for the model you want to delete.

  ```Python Snippet:dt_models_lifecycle

  service_client.delete_model(model_id)
  ```




  For Creating Twin you will need to provide Id of a digital Twin such as `my_twin` and the application/json digital twin based on the model created earlier. You can look at sample application/json [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/digitaltwins/azure-digitaltwins-core/samples/dtdl/digital_twins).

  ```Python Snippet:dt_digitaltwins_lifecycle
  digital_twin_id = 'digitalTwin-' + str(uuid.uuid4())
  temporary_twin = {
      "$metadata": {
          "$model": model_id
      },
      "$dtId": digital_twin_id,
      "Prop1": 42
  }

  created_twin = service_client.upsert_digital_twin(digital_twin_id, temporary_twin)
  print('Created Digital Twin:')
  print(created_twin)
  ```



  Getting a digital twin is extremely easy.
  ```Python Snippet:dt_digitaltwins_lifecycle
  get_twin = service_client.get_digital_twin(digital_twin_id)
  print('Get Digital Twin:')
  print(get_twin)
  ```



  Query the Azure Digital Twins instance for digital twins using the [Azure Digital Twins Query Store lanaguage](https://docs.microsoft.com/azure/digital-twins/concepts-query-language). Query calls support paging. Here's an example of how to query for digital twins and how to iterate over the results.

  Note that there may be a delay between before changes in your instance are reflected in queries.
  For more details on query limitations, see (https://docs.microsoft.com/azure/digital-twins/how-to-query-graph#query-limitations)

  ```Python Snippet:dt_digitaltwins_query
  query_expression = 'SELECT * FROM digitaltwins'
  query_result = service_client.query_twins(query_expression)
  print('DigitalTwins:')
  for twin in query_result:
      print(twin)
  ```



  Delete a digital twin simply by providing Id of a digital twin as below.

  ```Python Snippet:dt_digitaltwins_lifecycle
  service_client.delete_digital_twin(digital_twin_id)
  ```





  To update a component or in other words to replace, remove and/or add a component property or subproperty within Digital Twin, you would need Id of a digital twin, component name and application/json-patch+json operations to be performed on the specified digital twin's component. Here is the sample code on how to do it.

  ```Python Snippet:dt_component_lifecycle
  component_name = "Component1"
  patch = [
      {
          "op": "replace",
          "path": "/ComponentProp1",
          "value": "value2"
      }
  ]
  service_client.update_component(digital_twin_id, component_name, patch)
  ```



  Get a component by providing name of a component and Id of digital twin to which it belongs.

  ```Python Snippet:dt_component_lifecycle
  get_component = service_client.get_component(digital_twin_id, component_name)
  print('Get Component:')
  print(get_component)
  ```





  `upsert_relationship` creates a relationship on a digital twin provided with Id of a digital twin, name of relationship such as "contains", Id of an relationship such as "FloorContainsRoom" and an application/json relationship to be created. Must contain property with key "\$targetId" to specify the target of the relationship. Sample payloads for relationships can be found [here](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/digitaltwins/azure-digitaltwins-core/samples/dtdl/relationships/hospitalRelationships.json).

  ```Python Snippet:dt_scenario
  hospital_relationships = [
      {
          "$relationshipId": "BuildingHasFloor",
          "$sourceId": building_twin_id,
          "$relationshipName": "has",
          "$targetId": floor_twin_id,
          "isAccessRestricted": False
      },
      {
          "$relationshipId": "BuildingIsEquippedWithHVAC",
          "$sourceId": building_twin_id,
          "$relationshipName": "isEquippedWith",
          "$targetId": hvac_twin_id
      },
      {
          "$relationshipId": "HVACCoolsFloor",
          "$sourceId": hvac_twin_id,
          "$relationshipName": "controlsTemperature",
          "$targetId": floor_twin_id
      },
      {
          "$relationshipId": "FloorContainsRoom",
          "$sourceId": floor_twin_id,
          "$relationshipName": "contains",
          "$targetId": room_twin_id
      }
  ]

  for relationship in hospital_relationships:
      service_client.upsert_relationship(
          relationship["$sourceId"],
          relationship["$relationshipId"],
          relationship
      )
  ```



  `list_relationships` and `list_incoming_relationships` lists all the relationships and all incoming relationships respectively of a digital twin.

  ```Python Snippet:dt_relationships_list
  relationships = service_client.list_relationships(digital_twint_id)
  for relationship in relationships:
      print(relationship)
  ```

  ```Python Snippet:dt_incoming_relationships_list
  incoming_relationships = service_client.list_incoming_relationships(digital_twin_id)
  for incoming_relationship in incoming_relationships:
      print(incoming_relationship)
  ```





  To create an event route, provide an Id of an event route such as "myEventRouteId" and event route data containing the endpoint and optional filter like the example shown below.

  ```Python Snippet:dt_scenario
  event_route_id = 'eventRoute-' + str(uuid.uuid4())
  event_filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"
  route = DigitalTwinsEventRoute(
      endpoint_name=event_hub_endpoint_name,
      filter=event_filter
  )
  service_client.upsert_event_route(event_route_id, route)
  ```

  For more information on the event route filter language, see the "how to manage routes" [filter events documentation](https://github.com/Azure/azure-digital-twins/blob/private-preview/Documentation/how-to-manage-routes.md#filter-events).



  List a specific event route given event route Id or all event routes setting options with `list_event_routes`.

  ```Python Snippet:dt_event_routes_list
  event_routes = service_client.list_event_routes()
  for event_route in event_routes:
      print(event_route)
  ```



  Delete an event route given event route Id.

  ```Python Snippet:dt_scenario
  service_client.delete_event_route(event_route_id)
  ```



  To publish a telemetry message for a digital twin, you need to provide the digital twin Id, along with the payload on which telemetry that needs the update.

  ```Python Snippet:dt_publish_telemetry
  digita_twin_id = "<DIGITAL TWIN ID>"
  telemetry_payload = '{"Telemetry1": 5}'
  service_client.publish_telemetry(
      digita_twin_id,
      telemetry_payload
  )
  ```

  You can also publish a telemetry message for a specific component in a digital twin. In addition to the digital twin Id and payload, you need to specify the target component Id.

  ```Python Snippet:dt_publish_component_telemetry
  digita_twin_id = "<DIGITAL TWIN ID>"
  component_name = "<COMPONENT_NAME>"
  telemetry_payload = '{"Telemetry1": 5}'
  service_client.publish_component_telemetry(
      digita_twin_id,
      component_name,
      telemetry_payload
  )
  ```




  This library uses the standard logging 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 keyword argument:


  ```python Snippet:dt_digitaltwins_get.py
  import sys
  import logging


  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)
  handler = logging.StreamHandler(stream=sys.stdout)
  logger.addHandler(handler)


  service_client = DigitalTwinsClient(url, credential, logging_enable=True)
  ```


  ```python Snippet:dt_models_get.py
  import sys
  import logging


  logger = logging.getLogger('azure')
  logger.setLevel(logging.DEBUG)
  handler = logging.StreamHandler(stream=sys.stdout)
  logger.addHandler(handler)


  model = service_client.get_model(model_id, logging_enable=True)
  ```


  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.

  [azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity
  [azure_identity_pypi]: https://pypi.org/project/azure-identity/
  [default_cred_ref]: https://aka.ms/azsdk/python/identity/docs#azure.identity.DefaultAzureCredential
  [pip]: https://pypi.org/project/pip/






  If you encounter bugs or have suggestions, please
  [open an issue](https://github.com/Azure/azure-sdk-for-python/issues).



  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.




   - GA release





  - Update `azure-core` dependency to avoid inconsistent dependencies from being installed.



  - Python 2.7 and 3.6 are no longer supported. Please use Python version 3.7 or later.




  - The is the GA release containing the following changes:

  **API updates**
  - Added etag and match_condition parameters to upsert_digital_twin and upsert_relationship APIs to support conditional operation.
  - Renamed `EventRoute` model to `DigitalTwinsEventRoute`.
  - Removed unsed `azure.digitaltwins.core.QueryResult` object.
  - Renamed the `component_path` to `component_name`
  - Renamed the `payload` parameter to `telemetry` and made `message_id` a keyword-only parameter.

  **Bug Fixes**
  - The `relationship` parameter in `DigitalTwinsClient.upsert_relationship` is required and has been amended accordingly.
  - The `json_patch` parameter in `DigitalTwinsClient.update_relationship` is required and has been amended accordingly.
  - Renamed `models` parameter to `dtdl_models` in `DigitalTwinsClient.create_models`. This is now required.
  - The `dependencies_for` parameter in `DigitalTwinsClient.list_models` is optional and has been amended accordingly.
  - Match condition parameters have been fixed. Where invalid match conditions are supplied, a `ValueError` will be raised.
  - Fixed double await on async listing operations.

  **Documentation**
  - User Agent value updated according to guidelines.
  - Updated JSON patch parameter typehints to `List[Dict[str, object]]`.
  - Updated constructor credential typehint to `azure.core.credentials.TokenCredential`
  - Samples and documentation updated.




  * Initial Release


pkgId: 36bb1c1486912e77ce3645cb37355dafe124f4fc813feef579a4ccac0cc97cb3
name: python-azure-eventgrid
arch: src
version: 4.20.0
epoch: 0
release: 1
summary: Microsoft Azure Event Grid Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-eventgrid-4.20.0-1.src.rpm
checksum_type: sha256
description:
  Azure Event Grid is a fully-managed intelligent event routing service that allows for uniform event consumption using a publish-subscribe model.

  [Source code][python-eg-src]
  | [Package (PyPI)][python-eg-pypi]
  | [Package (Conda)](https://anaconda.org/microsoft/azure-eventgrid/)
  | [API reference documentation][python-eg-ref-docs]
  | [Product documentation][python-eg-product-docs]
  | [Samples][python-eg-samples]
  | [Changelog][python-eg-changelog]



  This is a GA release of Azure Event Grid's `EventGridPublisherClient` and `EventGridConsumerClient`. `EventGridPublisherClient` supports `send` for Event Grid Basic and Event Grid Namespaces. `EventGridConsumerClient` supports `receive`, `acknowledge` , `release`, `reject`, and `renew_locks` operations for Event Grid Namespaces. Please refer to the [samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventgrid/azure-eventgrid/samples) for further information.




  * Python 3.8 or later is required to use this package.
  * You must have an [Azure subscription][azure_subscription] and at least one of the following:
      * an Event Grid Namespace resource. To create an Event Grid Namespace resource follow [this tutorial](https://learn.microsoft.com/azure/event-grid/create-view-manage-namespaces).
      * an Event Grid Basic resource. To create an Event Grid Basic resource via the Azure portal follow this [step-by-step tutorial](https://docs.microsoft.com/azure/event-grid/custom-event-quickstart-portal). To create an Event Grid Basic resource via the [Azure CLI](https://docs.microsoft.com/cli/azure) follow this [tutorial](https://docs.microsoft.com/azure/event-grid/custom-event-quickstart)



  Azure Event Grid Namespaces supports both pull and push delivery. Azure Event Grid Basic supports only push delivery.
  More information on the two resource tiers can be found [here](https://learn.microsoft.com/azure/event-grid/choose-right-tier).

  **Note:** Azure Event Grid Namespaces only supports the Cloud Event v1.0 Schema.


  Install the Azure Event Grid client library for Python with [pip][pip]:

  ```bash
  pip install azure-eventgrid
  ```

  * An existing Event Grid Basic topic or domain, or Event Grid Namespace topic is required. You can create the resource using [Azure Portal][azure_portal_create_EG_resource] or [Azure CLI][azure_cli_link]

  If you use Azure CLI, replace `<resource-group-name>` and `<resource-name>` with your own unique names.



  ```
  az eventgrid namespace create --location <location> --resource-group <resource-group-name> --name <resource-name>
  ```



  ```
  az eventgrid namespace create topic --location <location> --resource-group <resource-group-name> --name <resource-name>
  ```


  In order to interact with the Event Grid service, you will need to create an instance of a client.
  An **endpoint** and **credential** are necessary to instantiate the client object.


  The default EventGridPublisherClient created is compatible with an Event Grid Basic Resource. To create an Event Grid Namespace compatible client, specify `namespace_topic="YOUR_TOPIC_NAME"` when instantiating the client.

  ```python

  client = EventGridPublisherClient(endpoint, credential, namespace_topic=YOUR_TOPIC_NAME)


  client = EventGridPublisherClient(endpoint, credential)
  ```

  EventGridConsumerClient only supports Event Grid Namespaces.
  ```python

  client = EventGridConsumerClient(endpoint, credential, namespace_topic=YOUR_TOPIC_NAME, subscription=YOUR_SUBSCRIPTION_NAME)
  ```



  Azure Event Grid provides integration with Azure Active Directory (Azure AD) for identity-based authentication of requests. With Azure AD, you can use role-based access control (RBAC) to grant access to your Azure Event Grid resources to users, groups, or applications.

  To send events to a topic or domain with a `TokenCredential`, the authenticated identity should have the "Event Grid Data Sender" role assigned.
  To receive events from a topic event subscription with a `TokenCredential`, the authenticated identity should have the "Event Grid Data Receiver" role assigned.
  To send and receive events to/from a topic with a `TokenCredential`, the authenticated identity should have the "Event Grid Data Contributor" role assigned.

  More about RBAC setup can be found [here](https://learn.microsoft.com/azure/role-based-access-control/role-assignments-steps).

  With the `azure-identity` package, you can seamlessly authorize requests in both development and production environments. To learn more about Azure Active Directory, see the [`azure-identity` README](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md).

  For example, you can use `DefaultAzureCredential` to construct a client which will authenticate using Azure Active Directory:

  <!-- SNIPPET:sample_authentication.client_auth_with_token_cred -->

  ```python
  from azure.identity import DefaultAzureCredential
  from azure.eventgrid import EventGridPublisherClient, EventGridEvent

  default_az_credential = DefaultAzureCredential()
  endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]
  client = EventGridPublisherClient(endpoint, default_az_credential)
  ```

  <!-- END SNIPPET -->




  You can find the Namespace endpoint within the Event Grid Namespace resource on the Azure portal. This will look like:
  `"<event-grid-namespace-name>.<namespace-location>.eventgrid.azure.net"`


  You can find the topic endpoint within the Event Grid Topic resource on the Azure portal. This will look like:
  `"https://<event-grid-topic-name>.<topic-location>.eventgrid.azure.net/api/events"`



  To use an Access key as the `credential` parameter,
  pass the key as a string into an instance of [AzureKeyCredential][azure-key-credential].

  > **Note:** The Access Key may be found in the azure portal in the "Access Keys" menu of the Event Grid Topic resource.  They may also be obtained via the azure CLI, or the `azure-mgmt-eventgrid` library. A guide for getting access keys can be found [here](https://docs.microsoft.com/azure/event-grid/get-access-keys).

  <!-- SNIPPET:sample_authentication.client_auth_with_key_cred -->

  ```python
  import os
  from azure.eventgrid import EventGridPublisherClient
  from azure.core.credentials import AzureKeyCredential

  topic_key = os.environ["EVENTGRID_TOPIC_KEY"]
  endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]

  credential_key = AzureKeyCredential(topic_key)
  client = EventGridPublisherClient(endpoint, credential_key)
  ```

  <!-- END SNIPPET -->

  > **Note:** A Basic client may also be authenticated via SAS signature, using the `AzureSasCredential`. A sample demonstrating this, is available [here][python-eg-sample-send-using-sas] ([async_version][python-eg-sample-send-using-sas-async]).

  > **Note:** The `generate_sas` method can be used to generate a shared access signature. A sample demonstrating this can be seen [here][python-eg-generate-sas].





  A **[namespace](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#namespaces)** is a management container for other resources. It allows for grouping of related resources in order to manage them under one subscription.



  A **[namespace topic](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#namespace-topics)** is a topic that is created within an Event Grid namespace. The client publishes events to an HTTP namespace endpoint specifying a namespace topic where published events are logically contained. A namespace topic only supports the CloudEvent v1.0 schema.



  An **[event subscription](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#event-subscriptions)** is a configuration resource associated with a single topic.





  A **[topic](https://docs.microsoft.com/azure/event-grid/concepts#topics)** is a channel within the Event Grid service to send events. The event schema that a topic accepts is decided at topic creation time. If events of a schema type are sent to a topic that requires a different schema type, errors will be raised.


  An event **[domain](https://docs.microsoft.com/azure/event-grid/event-domains)** is a management tool for large numbers of Event Grid topics related to the same application. They allow you to publish events to thousands of topics. Domains also give you authorization and authentication control over each topic. For more information, visit [Event domain overview](https://docs.microsoft.com/azure/event-grid/event-domains).


  An **[event](https://docs.microsoft.com/azure/event-grid/concepts#events)** is the smallest amount of information that fully describes something that happened in the system. When a custom topic or domain is created, you must specify the schema that will be used when publishing events.

  Event Grid supports multiple schemas for encoding events.


  A **[system topic](https://docs.microsoft.com/azure/event-grid/system-topics)** in Event Grid represents one or more events published by Azure services such as Azure Storage or Azure Event Hubs. For example, a system topic may represent all blob events or only blob creation and blob deletion events published for a specific storage account.

  The names of the various event types for the system events published to Azure Event Grid are available in `azure.eventgrid.SystemEventNames`.
  For complete list of recognizable system topics, visit [System Topics](https://docs.microsoft.com/azure/event-grid/system-topics).

   For more information about the key concepts on Event Grid, see [Concepts in Azure Event Grid][publisher-service-doc].



  `EventGridPublisherClient` provides operations to send event data to a resource specified during client initialization.

  If you are using Event Grid Basic, regardless of the schema that your topic or domain is configured to use, `EventGridPublisherClient` will be used to publish events to it. Use the `send` method to publish events.

  The following formats of events are allowed to be sent to an Event Grid Basic resource:
  - A list or a single instance of strongly typed EventGridEvents.
  - A dict representation of a serialized EventGridEvent object.
  - A list or a single instance of strongly typed CloudEvents.
  - A dict representation of a serialized CloudEvent object.

  - A dict representation of any Custom Schema.

  The following formats of events are allowed to be sent to an Event Grid Namespace resource, when a namespace topic is specified:

  * A list of single instance of strongly typed CloudEvents.
  * A dict representation of a serialized CloudEvent object.

  Please have a look at the [samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventgrid/azure-eventgrid/samples) for detailed examples.



  Event Grid on Kubernetes with Azure Arc is an offering that allows you to run Event Grid on your own Kubernetes cluster. This capability is enabled by the use of Azure Arc enabled Kubernetes. Through Azure Arc enabled Kubernetes, a supported Kubernetes cluster connects to Azure. Once connected, you are able to install Event Grid on it. Learn more about it [here](https://docs.microsoft.com/azure/event-grid/kubernetes/overview).



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

  * [Send a Cloud Event](#send-a-cloud-event)
  * [Send Multiple Events](#send-multiple-events)
  * [Receive and Process Events from Namespace](#receive-and-process-events-from-namespace)



  This example publishes a Cloud event.

  ```python
  import os
  from azure.core.credentials import AzureKeyCredential
  from azure.core.messaging import CloudEvent
  from azure.eventgrid import EventGridPublisherClient

  key = os.environ["EVENTGRID_KEY"]
  endpoint = os.environ["EVENTGRID_ENDPOINT"]
  topic_name = os.environ["EVENTGRID_TOPIC_NAME"]


  event = CloudEvent(
      type="Azure.Sdk.Sample",
      source="https://egsample.dev/sampleevent",
      data={"team": "azure-sdk"}
  )

  credential = AzureKeyCredential(key)
  client = EventGridPublisherClient(endpoint, credential, namespace_topic=topic_name)

  client.send(event)
  ```



  It is possible to send events as a batch when sending multiple events to a topic or a domain. This example sends a list of CloudEvents using the send method.

  **WARNING:** When sending a list of multiple events at one time, iterating over and sending each event will not result in optimal performance. For best performance, it is highly recommended to send a list of events.

  ```python
  import os
  from azure.core.credentials import AzureKeyCredential
  from azure.core.messaging import CloudEvent
  from azure.eventgrid import EventGridPublisherClient

  key = os.environ["EVENTGRID_KEY"]
  endpoint = os.environ["EVENTGRID_ENDPOINT"]
  topic_name = os.environ["EVENTGRID_TOPIC_NAME"]

  event0 = CloudEvent(
      type="Azure.Sdk.Sample",
      source="https://egsample.dev/sampleevent",
      data={"team": "azure-sdk"}
  )
  event1 = CloudEvent(
      type="Azure.Sdk.Sample",
      source="https://egsample.dev/sampleevent",
      data={"team2": "azure-eventgrid"}
  )

  events = [event0, event1]

  credential = AzureKeyCredential(key)
  client = EventGridPublisherClient(endpoint, credential, namespace_topic=topic_name)

  client.send(events)
  ```



  Use EventGridConsumerClient's receive function to receive CloudEvents from a Namespace event subscription. Then try to acknowledge, reject, release or renew the locks.

  ```python
  import os
  import uuid
  import datetime as dt
  from azure.core.credentials import AzureKeyCredential
  from azure.eventgrid import EventGridConsumerClient

  key = os.environ["EVENTGRID_KEY"]
  endpoint = os.environ["EVENTGRID_ENDPOINT"]
  topic_name = os.environ["EVENTGRID_TOPIC_NAME"]
  sub_name = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"]

  credential = AzureKeyCredential(key)
  client = EventGridConsumerClient(endpoint, credential, namespace_topic=topic_name, subscription=sub_name)

  events = client.receive(max_events=4)

  for detail in events.value:
      data = detail.event.data
      broker_properties = detail.broker_properties
      if data == "release":
          release_events.append(broker_properties.lock_token)
      elif data == "acknowledge":
          acknowledge_events.append(broker_properties.lock_token)
      else:
          reject_events.append(broker_properties.lock_token)

      
      renew_tokens = e.broker_properties.lock_token
      renew_result = client.renew_locks(
          lock_tokens=renew_tokens,
      )


  release_result = client.release(
      lock_tokens=release_events,
  )

  ack_result = client.acknowledge(
      lock_tokens=acknowledge_events,
  )

  reject_result = client.reject(
      lock_tokens=reject_events,
  )

  ```



  You can use OpenTelemetry for Python as usual with Event Grid since it's compatible with azure-core tracing integration.

  Here is an example of using OpenTelemetry to trace sending a CloudEvent.

  First, set OpenTelemetry as enabled tracing plugin for Event Grid.

  ```python
  from azure.core.settings import settings
  from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan

  settings.tracing_implementation = OpenTelemetrySpan
  ```

  Regular open telemetry usage from here. See [OpenTelemetry](https://github.com/open-telemetry/opentelemetry-python) for details.
  This example uses a simple console exporter to export the traces. Any exporter can be used here including `azure-monitor-opentelemetry-exporter`, `jaeger`, `zipkin` etc.

  ```python
  from opentelemetry import trace
  from opentelemetry.sdk.trace import TracerProvider
  from opentelemetry.sdk.trace.export import ConsoleSpanExporter
  from opentelemetry.sdk.trace.export import SimpleSpanProcessor  # this requires opentelemetry >= 1.0.0


  exporter = ConsoleSpanExporter()

  trace.set_tracer_provider(TracerProvider())
  tracer = trace.get_tracer(__name__)
  trace.get_tracer_provider().add_span_processor(
      SimpleSpanProcessor(exporter)
  )
  ```

  Once the `tracer` and `exporter` are set, please follow the example below to start collecting traces while using the `send` method from the `EventGridClient` to send a CloudEvent object.

  ```python
  import os
  from azure.eventgrid import EventGridPublisherClient
  from azure.core.messaging import CloudEvent
  from azure.core.credentials import AzureKeyCredential

  hostname = os.environ['CLOUD_TOPIC_HOSTNAME']
  key = AzureKeyCredential(os.environ['CLOUD_ACCESS_KEY'])
  cloud_event = CloudEvent(
      source = 'demo',
      type = 'sdk.demo',
      data = {'test': 'hello'},
  )
  with tracer.start_as_current_span(name="MyApplication"):
      client = EventGridPublisherClient(hostname, key)
      client.send(cloud_event)
  ```



  - Enable `azure.eventgrid` logger to collect traces from the library.


  Event Grid client library will raise exceptions defined in [Azure Core][azure_core_exceptions].


  This library uses the standard
  [logging][python_logging] library for logging.
  Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
  level.



  Optional keyword arguments can be passed in at the client and per-operation level.
  The azure-core [reference documentation][azure_core_ref_docs]
  describes available configurations for retries, logging, transport protocols, and more.



  The following section provides several code snippets illustrating common patterns used in the Event Grid Python API.



  These code samples show common champion scenario operations with the Azure Event Grid client library.



  * Authenticate the client: [sample_namespace_authentication_async.py][python-eg-namespace-authenticate-async]
  * Publish to the namespace topic: [sample_publish_cloud_event_async.py][python-eg-namespace-publish-cloud-async]
  * Consume and Process from an event subscription: [sample_consume_process_events.py][python-eg-namespace-consume-async]




  * Generate Shared Access Signature: [sample_generate_sas.py][python-eg-generate-sas]

  * Authenticate the client: [sample_authentication.py][python-eg-auth] ([async_version][python-eg-auth-async])

  * Publish events to a topic using SAS: [sample_publish_events_to_a_topic_using_sas_credential_async.py][python-eg-sample-send-using-sas] ([async_version][python-eg-sample-send-using-sas-async])
  * Publish Event Grid Events to a topic: [sample_publish_eg_events_to_a_topic.py][python-eg-sample-eg-event] ([async_version][python-eg-sample-eg-event-async])
  * Publish Event Grid Events to a domain topic: [sample_publish_eg_events_to_a_domain_topic.py][python-eg-sample-eg-event-to-domain] ([async_version][python-eg-sample-eg-event-to-domain-async])
  * Publish a Cloud Event: [sample_publish_events_using_cloud_events_1.0_schema.py][python-eg-sample-send-cloudevent] ([async_version][python-eg-sample-send-cloudevent-async])
  * Publish a Custom Schema: [sample_publish_custom_schema_to_a_topic.py][python-eg-publish-custom-schema] ([async_version][python-eg-publish-custom-schema-async])

  The following samples cover publishing and consuming `dict` representations of EventGridEvents and CloudEvents.
  * Publish EventGridEvent as dict like representation: [sample_publish_eg_event_using_dict.py][python-eg-sample-send-eg-as-dict] ([async_version][python-eg-sample-send-eg-as-dict-async])

  * Publish CloudEvent as dict like representation: [sample_publish_cloud_event_using_dict.py][python-eg-sample-send-cloudevent-as-dict] ([async_version][python-eg-sample-send-cloudevent-as-dict-async])

  * Consume a Custom Payload of raw cloudevent data: [sample_consume_custom_payload.py][python-eg-sample-consume-custom-payload]

  More samples can be found [here][python-eg-samples].

  * More samples related to the send scenario can be seen [here][python-eg-publish-samples].
  * To see more samples related to consuming a payload from different messaging services as a typed object, please visit [Consume Samples][python-eg-consume-samples]



  For more extensive documentation on Azure Event Grid, see the [Event Grid documentation][python-eg-product-docs] on docs.microsoft.com.


  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 [cla.microsoft.com][cla].

  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][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments.

  <!-- LINKS -->

  [azure_cli_link]: https://pypi.org/project/azure-cli/
  [python-eg-src]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventgrid/azure-eventgrid
  [python-eg-pypi]: https://pypi.org/project/azure-eventgrid
  [python-eg-product-docs]: https://docs.microsoft.com/azure/event-grid/overview
  [python-eg-ref-docs]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-eventgrid/latest/index.html
  [publisher-service-doc]: https://docs.microsoft.com/azure/event-grid/concepts
  [python-eg-samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventgrid/azure-eventgrid/samples
  [python-eg-changelog]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventgrid/azure-eventgrid/CHANGELOG.md
  [pip]: https://pypi.org/project/pip/

  [azure_portal_create_EG_resource]: https://ms.portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.EventGrid%2Ftopics
  [azure-key-credential]: https://aka.ms/azsdk/python/core/azurekeycredential
  [azure_core_exceptions]: https://aka.ms/azsdk/python/core/docs#module-azure.core.exceptions
  [python_logging]: https://docs.python.org/3/library/logging.html
  [azure_core_ref_docs]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core#configurations
  [azure_subscription]: https://azure.microsoft.com/free/

  [python-eg-auth]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_authentication.py
  [python-eg-generate-sas]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_generate_sas.py
  [python-eg-sample-send-using-sas]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_events_to_a_topic_using_sas_credential.py
  [python-eg-sample-eg-event]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_eg_events_to_a_topic.py
  [python-eg-sample-eg-event-to-domain]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_eg_events_to_a_domain.py
  [python-eg-sample-send-cloudevent]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py
  [python-eg-publish-custom-schema]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_custom_schema_to_a_topic.py
  [python-eg-sample-send-eg-as-dict]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_eg_event_using_dict.py
  [python-eg-sample-send-cloudevent-as-dict]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_publish_cloud_event_using_dict.py

  [python-eg-auth-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_authentication_async.py
  [python-eg-sample-send-using-sas-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_events_to_a_topic_using_sas_credential_async.py
  [python-eg-sample-eg-event-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_eg_events_to_a_topic_async.py
  [python-eg-sample-eg-event-to-domain-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_eg_events_to_a_domain_async.py
  [python-eg-sample-send-cloudevent-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py
  [python-eg-publish-custom-schema-async]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_custom_schema_to_a_topic_async.py
  [python-eg-sample-send-eg-as-dict-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_eg_event_using_dict_async.py
  [python-eg-sample-send-cloudevent-as-dict-async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/async_samples/sample_publish_cloud_event_using_dict_async.py

  [python-eg-publish-samples]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/publish_samples
  [python-eg-consume-samples]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/consume_samples
  [python-eg-sample-consume-custom-payload]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/basic/sync_samples/sample_consume_custom_payload.py


  [python-eg-namespace-authenticate]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/sync_samples/sample_namespace_authentication.py
  [python-eg-namespace-publish-cncf]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/sync_samples/sample_publish_cncf_events.py
  [python-eg-namespace-publish-cloud]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/sync_samples/sample_publish_cloud_event.py
  [python-eg-namespace-consume]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/samples/sync_samples/sample_consume_process_events.py


  [python-eg-namespace-authenticate-async]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_namespace_authentication_async.py
  [python-eg-namespace-publish-cncf-async]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_publish_cncf_events_async.py
  [python-eg-namespace-publish-cloud-async]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_publish_cloud_event_async.py
  [python-eg-namespace-consume-async]:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_consume_process_events_async.py

  [cla]: https://cla.microsoft.com
  [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
  [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
  [coc_contact]: mailto:opencode@microsoft.com


pkgId: 0cf17b7ee9cebe8587353337e32266d1fef9998cedefa81e6e1c2a7a3df22583
name: python-azure-eventhub
arch: src
version: 5.12.1
epoch: 0
release: 1
summary: Microsoft Azure Event Hubs Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventhub/azure-eventhub
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-eventhub-5.12.1-1.src.rpm
checksum_type: sha256
description:
  Azure Event Hubs is a highly scalable publish-subscribe service that can ingest millions of events per second and stream
  them to multiple consumers. This lets you process and analyze the massive amounts of data produced by your connected
  devices and applications. Once Event Hubs has collected the data, you can retrieve, transform, and store it by using
  any real-time analytics provider or with batching/storage adapters. If you would like to know more about Azure Event Hubs,
  you may wish to review: [What is Event Hubs](https://docs.microsoft.com/azure/event-hubs/event-hubs-about)?

  The Azure Event Hubs client library allows for publishing and consuming of Azure Event Hubs events and may be used to:

  - Emit telemetry about your application for business intelligence and diagnostic purposes.
  - Publish facts about the state of your application which interested parties may observe and use as a trigger for taking action.
  - Observe interesting operations and interactions happening within your business or other ecosystem, allowing loosely coupled systems to interact without the need to bind them together.
  - Receive events from one or more publishers, transform them to better meet the needs of your ecosystem, then publish the transformed events to a new stream for consumers to observe.

  [Source code](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/)
  | [Package (PyPi)](https://pypi.org/project/azure-eventhub/)
  | [Package (Conda)](https://anaconda.org/microsoft/azure-eventhub/)
  | [API reference documentation][api_reference]
  | [Product documentation](https://docs.microsoft.com/azure/event-hubs/)
  | [Samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventhub/azure-eventhub/samples)





  - Python 3.8 or later.
  - **Microsoft Azure Subscription:**  To use Azure services, including Azure Event Hubs, you'll need a subscription.
  If you do not have an existing Azure account, you may sign up for a free trial or use your MSDN subscriber benefits when you [create an account](https://azure.microsoft.com/free/).

  - **Event Hubs namespace with an Event Hub:** To interact with Azure Event Hubs, you'll also need to have a namespace and Event Hub  available.
  If you are not familiar with creating Azure resources, you may wish to follow the step-by-step guide
  for [creating an Event Hub using the Azure portal](https://docs.microsoft.com/azure/event-hubs/event-hubs-create).
  There, you can also find detailed instructions for using the Azure CLI, Azure PowerShell, or Azure Resource Manager (ARM) templates to create an Event Hub.



  Install the Azure Event Hubs client library for Python with pip:

  ```
  $ pip install azure-eventhub
  ```



  Interaction with Event Hubs starts with an instance of EventHubConsumerClient or EventHubProducerClient class. You need either the host name, SAS/AAD credential and event hub name or a connection string to instantiate the client object.

  **[Create client from connection string:](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples/sync_samples/connection_string_authentication.py)**

  For the Event Hubs client library to interact with an Event Hub, the easiest means is to use a connection string, which is created automatically when creating an Event Hubs namespace.
  If you aren't familiar with shared access policies in Azure, you may wish to follow the step-by-step guide to [get an Event Hubs connection string](https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string).

  - The `from_connection_string` method takes the connection string of the form
  `Endpoint=sb://<yournamespace>.servicebus.windows.net/;SharedAccessKeyName=<yoursharedaccesskeyname>;SharedAccessKey=<yoursharedaccesskey>` and
  entity name to your Event Hub instance. You can get the connection string from the [Azure portal](https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string#get-connection-string-from-the-portal).

  **[Create client using the azure-identity library:](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples/sync_samples/client_identity_authentication.py)**

  Alternately, one can use a Credential object to authenticate via AAD with the azure-identity package.

  - This constructor demonstrated in the sample linked above takes the host name and entity name of your Event Hub instance and credential that implements the
  [TokenCredential](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/azure/core/credentials.py)
  protocol. There are implementations of the `TokenCredential` protocol available in the
  [azure-identity package](https://pypi.org/project/azure-identity/). The host name is of the format `<yournamespace.servicebus.windows.net>`.
  - To use the credential types provided by `azure-identity`, please install the package:
  ```pip install azure-identity```
  - Additionally, to use the async API,  you must first install an async transport, such as [`aiohttp`](https://pypi.org/project/aiohttp/):
  ```pip install aiohttp```
  - When using Azure Active Directory, your principal must be assigned a role which allows access to Event Hubs, such as the
  Azure Event Hubs Data Owner role. For more information about using Azure Active Directory authorization with Event Hubs,
  please refer to [the associated documentation](https://docs.microsoft.com/azure/event-hubs/authorize-access-azure-active-directory).



  - An **EventHubProducerClient** is a source of telemetry data, diagnostics information, usage logs, or other log data,
  as part of an embedded device solution, a mobile device application, a game title running on a console or other device,
  some client or server based business solution, or a web site.

  - An **EventHubConsumerClient** picks up such information from the Event Hub and processes it. Processing may involve aggregation,
  complex computation, and filtering. Processing may also involve distribution or storage of the information in a raw or transformed fashion.
  Event Hub consumers are often robust and high-scale platform infrastructure parts with built-in analytics capabilities,
  like Azure Stream Analytics, Apache Spark, or Apache Storm.

  - A **partition** is an ordered sequence of events that is held in an Event Hub. Azure Event Hubs provides message streaming
  through a partitioned consumer pattern in which each consumer only reads a specific subset, or partition, of the message stream.
  As newer events arrive, they are added to the end of this sequence. The number of partitions is specified at the time an Event Hub is created and cannot be changed.

  - A **consumer group** is a view of an entire Event Hub. Consumer groups enable multiple consuming applications to each
  have a separate view of the event stream, and to read the stream independently at their own pace and from their own position.
  There can be at most 5 concurrent readers on a partition per consumer group; however it is recommended that there is only
  one active consumer for a given partition and consumer group pairing. Each active reader receives all of the events from
  its partition; if there are multiple readers on the same partition, then they will receive duplicate events.

  For more concepts and deeper discussion, see: [Event Hubs Features](https://docs.microsoft.com/azure/event-hubs/event-hubs-features).
  Also, the concepts for AMQP are well documented in [OASIS Advanced Messaging Queuing Protocol (AMQP) Version 1.0](https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-overview-v1.0-os.html).



  We do not guarantee that the EventHubProducerClient or EventHubConsumerClient are thread-safe. We do not recommend reusing these instances across threads. It is up to the running application to use these classes in a thread-safe manner.

  The data model type, `EventDataBatch` is not thread-safe. It should not be shared across threads nor used concurrently with client methods.



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

  - [Inspect an Event Hub](#inspect-an-event-hub)
  - [Publish events to an Event Hub](#publish-events-to-an-event-hub)
  - [Consume events from an Event Hub](#consume-events-from-an-event-hub)
  - [Consume events from an Event Hub in batches](#consume-events-from-an-event-hub-in-batches)
  - [Publish events to an Event Hub asynchronously](#publish-events-to-an-event-hub-asynchronously)
  - [Consume events from an Event Hub asynchronously](#consume-events-from-an-event-hub-asynchronously)
  - [Consume events from an Event Hub in batches asynchronously](#consume-events-from-an-event-hub-in-batches-asynchronously)
  - [Consume events and save checkpoints using a checkpoint store](#consume-events-and-save-checkpoints-using-a-checkpoint-store)
  - [Use EventHubConsumerClient to work with IoT Hub](#use-eventhubconsumerclient-to-work-with-iot-hub)



  Get the partition ids of an Event Hub.

  <!-- SNIPPET:connection_string_authentication.connection_string_authentication -->

  ```python
  import os
  from azure.eventhub import EventHubConsumerClient

  CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"]
  EVENTHUB_NAME = os.environ['EVENT_HUB_NAME']

  consumer_client = EventHubConsumerClient.from_connection_string(
      conn_str=CONNECTION_STR,
      consumer_group='$Default',
      eventhub_name=EVENTHUB_NAME,
  )

  with consumer_client:
      pass # consumer_client is now ready to be used.
  ```

  <!-- END SNIPPET -->



  Use the `create_batch` method on `EventHubProducerClient` to create an `EventDataBatch` object which can then be sent using the `send_batch` method.
  Events may be added to the `EventDataBatch` using the `add` method until the maximum batch size limit in bytes has been reached.

  <!-- SNIPPET:send.send_event_data_batch -->

  ```python
  def send_event_data_batch(producer):
      
      
      event_data_batch = producer.create_batch()
      event_data_batch.add(EventData('Single message'))
      producer.send_batch(event_data_batch)
  ```

  <!-- END SNIPPET -->



  There are multiple ways to consume events from an EventHub.  To simply trigger a callback when an event is received,
  the `EventHubConsumerClient.receive` method will be of use as follows:

  ```python
  import logging
  from azure.eventhub import EventHubConsumerClient

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'
  client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group, eventhub_name=eventhub_name)

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  def on_event(partition_context, event):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      partition_context.update_checkpoint(event)

  with client:
      client.receive(
          on_event=on_event,
          starting_position="-1",  # "-1" is from the beginning of the partition.
      )
      
      
  ```



  Whereas the above sample triggers the callback for each message as it is received, the following sample
  triggers the callback on a batch of events, attempting to receive a number at a time.

  ```python
  import logging
  from azure.eventhub import EventHubConsumerClient

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'
  client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group, eventhub_name=eventhub_name)

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  def on_event_batch(partition_context, events):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      partition_context.update_checkpoint()

  with client:
      client.receive_batch(
          on_event_batch=on_event_batch,
          starting_position="-1",  # "-1" is from the beginning of the partition.
      )
      
      
  ```



  Use the `create_batch` method on `EventHubProducer` to create an `EventDataBatch` object which can then be sent using the `send_batch` method.
  Events may be added to the `EventDataBatch` using the `add` method until the maximum batch size limit in bytes has been reached.
  ```python
  import asyncio
  from azure.eventhub.aio import EventHubProducerClient  # The package name suffixed with ".aio" for async
  from azure.eventhub import EventData

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  async def create_batch(client):
      event_data_batch = await client.create_batch()
      can_add = True
      while can_add:
          try:
              event_data_batch.add(EventData('Message inside EventBatchData'))
          except ValueError:
              can_add = False  # EventDataBatch object reaches max_size.
      return event_data_batch

  async def send():
      client = EventHubProducerClient.from_connection_string(connection_str, eventhub_name=eventhub_name)
      batch_data = await create_batch(client)
      async with client:
          await client.send_batch(batch_data)

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(send())
  ```



  This SDK supports both synchronous and asyncio based code.  To receive as demonstrated in the samples above, but within
  aio, one would need the following:

  ```python
  import logging
  import asyncio
  from azure.eventhub.aio import EventHubConsumerClient

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  async def on_event(partition_context, event):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      await partition_context.update_checkpoint(event)

  async def receive():
      client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group, eventhub_name=eventhub_name)
      async with client:
          await client.receive(
              on_event=on_event,
              starting_position="-1",  # "-1" is from the beginning of the partition.
          )
          
          

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(receive())
  ```



  All synchronous functions are supported in aio as well.  As demonstrated above for synchronous batch receipt, one can accomplish
  the same within asyncio as follows:

  ```python
  import logging
  import asyncio
  from azure.eventhub.aio import EventHubConsumerClient

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  async def on_event_batch(partition_context, events):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      await partition_context.update_checkpoint()

  async def receive_batch():
      client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group, eventhub_name=eventhub_name)
      async with client:
          await client.receive_batch(
              on_event_batch=on_event_batch,
              starting_position="-1",  # "-1" is from the beginning of the partition.
          )
          
          

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(receive_batch())
  ```



  `EventHubConsumerClient` is a high level construct which allows you to receive events from multiple partitions at once
  and load balance with other consumers using the same Event Hub and consumer group.

  This also allows the user to track progress when events are processed using checkpoints.

  A checkpoint is meant to represent the last successfully processed event by the user from a particular partition of
  a consumer group in an Event Hub instance. The `EventHubConsumerClient` uses an instance of `CheckpointStore` to update checkpoints
  and to store the relevant information required by the load balancing algorithm.

  Search pypi with the prefix `azure-eventhub-checkpointstore` to
  find packages that support this and use the `CheckpointStore` implementation from one such package. Please note that both sync and async libraries are provided.

  In the below example, we create an instance of `EventHubConsumerClient` and use a `BlobCheckpointStore`. You need
  to [create an Azure Storage account](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal)
  and a [Blob Container](https://docs.microsoft.com/azure/storage/blobs/storage-quickstart-blobs-portal#create-a-container) to run the code.

  [Azure Blob Storage Checkpoint Store Async](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub-checkpointstoreblob-aio)
  and [Azure Blob Storage Checkpoint Store Sync](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub-checkpointstoreblob)
  are one of the `CheckpointStore` implementations we provide that applies Azure Blob Storage as the persistent store.


  ```python
  import asyncio

  from azure.eventhub.aio import EventHubConsumerClient
  from azure.eventhub.extensions.checkpointstoreblobaio import BlobCheckpointStore

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'
  storage_connection_str = '<< CONNECTION STRING FOR THE STORAGE >>'
  container_name = '<<NAME OF THE BLOB CONTAINER>>'

  async def on_event(partition_context, event):
      
      await partition_context.update_checkpoint(event)  # Or update_checkpoint every N events for better performance.

  async def receive(client):
      await client.receive(
          on_event=on_event,
          starting_position="-1",  # "-1" is from the beginning of the partition.
      )

  async def main():
      checkpoint_store = BlobCheckpointStore.from_connection_string(storage_connection_str, container_name)
      client = EventHubConsumerClient.from_connection_string(
          connection_str,
          consumer_group,
          eventhub_name=eventhub_name,
          checkpoint_store=checkpoint_store,  # For load balancing and checkpoint. Leave None for no load balancing
      )
      async with client:
          await receive(client)

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(main())
  ```



  You can use `EventHubConsumerClient` to work with IoT Hub as well. This is useful for receiving telemetry data of IoT Hub from the
  linked EventHub. The associated connection string will not have send claims, hence sending events is not possible.

  Please notice that the connection string needs to be for an [Event Hub-compatible endpoint](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messages-read-builtin),
  e.g. "Endpoint=sb://my-iothub-namespace-[uid].servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-iot-hub-name"

  There are two ways to get the Event Hubs compatible endpoint:
  - Manually get the "Built-in endpoints" of the IoT Hub in Azure Portal and receive from it.
  ```python
  from azure.eventhub import EventHubConsumerClient

  connection_str = 'Endpoint=sb://my-iothub-namespace-[uid].servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-iot-hub-name'
  consumer_group = '<< CONSUMER GROUP >>'
  client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group)

  partition_ids = client.get_partition_ids()
  ```
  - Programmatically retrieve the built-in Event Hubs compatible endpoint.
  Refer to [IoT Hub Connection String Sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples/async_samples/iot_hub_connection_string_receive_async.py).



  See the `azure-eventhub` [troubleshooting guide](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/TROUBLESHOOTING.md) for details on how to diagnose various failure scenarios.



  - Enable `azure.eventhub` logger to collect traces from the library.
  - Enable AMQP frame level trace by setting `logging_enable=True` when creating the client.
  - Refer to [this guide](https://learn.microsoft.com/azure/developer/python/sdk/azure-sdk-logging) on configuring logging for Azure libraries for Python for additional information.

  ```python
  import logging
  import sys

  handler = logging.StreamHandler(stream=sys.stdout)
  logger = logging.getLogger('azure.eventhub')
  logger.setLevel(logging.DEBUG)
  logger.addHandler(handler)

  ...

  from azure.eventhub import EventHubProducerClient, EventHubConsumerClient

  producer = EventHubProducerClient(..., logging_enable=True)
  consumer = EventHubConsumerClient(..., logging_enable=True)
  ```





  Please take a look at the [samples](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples) directory for detailed examples of how to use this library to send and receive events to/from Event Hubs.



  Reference documentation is available [here](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-eventhub/latest/azure.eventhub.html).



  The EventHubs SDK integrates nicely with the [Schema Registry][schemaregistry_service] service and [Avro][avro].
  For more information, please refer to [Schema Registry SDK][schemaregistry_repo] and [Schema Registry Avro Encoder SDK][schemaregistry_avroencoder_repo].



  The Azure Event Hubs client library is now based on a pure Python AMQP implementation. `uAMQP` has been removed as required dependency.

  To use `uAMQP` as the underlying transport:

  1. Install `uamqp` with pip.

  ```
  $ pip install uamqp
  ```

  2. Pass `uamqp_transport=True` during client construction.

  ```python
  from azure.eventhub import EventHubProducerClient, EventHubConsumerClient

  connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  client = EventHubProducerClient.from_connection_string(
      connection_str, eventhub_name=eventhub_name, uamqp_transport=True
  )
  client = EventHubConsumerClient.from_connection_string(
      connection_str, consumer_group, eventhub_name=eventhub_name, uamqp_transport=True
  )
  ```

  Note: The `message` attribute on `EventData`/`EventDataBatch`, which previously exposed the `uamqp.Message`, has been deprecated.
   The "Legacy" objects returned by `EventData.message`/`EventDataBatch.message` have been introduced to help facilitate the transition.



  If [uAMQP](https://pypi.org/project/uamqp/) is intended to be used as the underlying AMQP protocol implementation for `azure-eventhub`,
  uAMQP wheels can be found for most major operating systems.

  If you intend to use `uAMQP` and you're running on a platform for which uAMQP wheels are not provided, please follow
   the [uAMQP Installation](https://github.com/Azure/azure-uamqp-python#installation) guidance to install from source.



  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.



  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.

  [avro]: https://avro.apache.org/
  [api_reference]: https://docs.microsoft.com/python/api/overview/azure/eventhub-readme
  [schemaregistry_service]: https://aka.ms/schemaregistry
  [schemaregistry_repo]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/schemaregistry/azure-schemaregistry
  [schemaregistry_avroencoder_repo]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/schemaregistry/azure-schemaregistry-avroencoder

  ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python/sdk/eventhub/azure-eventhub/README.png)








  - Fixed a bug where the correct URI was not being used for consumer authentication, causing issues when assigning roles at the consumer group level. ([#35337](https://github.com/Azure/azure-sdk-for-python/issues/35337))





  - Added support for non-tls connections (#34272)





  - Fixed a bug where using `EventHubProducerClient` in buffered mode could potentially drop a buffered message without actually sending it. ([#34712](https://github.com/Azure/azure-sdk-for-python/pull/34712))



  - Updated network trace logging to replace `None` values in AMQP connection info with empty strings as per the OpenTelemetry specification.



  This version and all future versions will require Python 3.8+. Python 3.7 is no longer supported.



  - Added `keep_alive` functionality on EventHubProducerClient to allow for long-living producers. [#33726](https://github.com/Azure/azure-sdk-for-python/issues/33726)



  - Added support for Python 3.12.





  - Fixed a pyAMQP error where events split across multiple TransferFrames were depleting the link credit by more than 1 credit per message. ([#32767](https://github.com/Azure/azure-sdk-for-python/pull/32767))





  - A new float keyword argument `socket_timeout` has been added to the sync and async `EventHubConsumerClient` and `EventHubProducerClient`.



  - Fixed bug [#31258](https://github.com/Azure/azure-sdk-for-python/issues/31258) where async `BlobCheckpointStore` was reprocessing old events after an error.





  - Fixed the error `end frame received on invalid channel` which was raised when a disconnect was sent by the service ([#30860](https://github.com/Azure/azure-sdk-for-python/pull/30860))
  - Fixed the error `link already closed` which was raised when the client was closing and disconnecting from the service ([#30836](https://github.com/Azure/azure-sdk-for-python/pull/30836))



   - Updated tracing ([#29934](https://github.com/Azure/azure-sdk-for-python/pull/29934)):
     - Span names renamed:
       - `Azure.EventHubs.send` to `EventHubs.send`
       - `Azure.EventHubs.message` to `EventHubs.message`
       - `Azure.EventHubs.process` to `EventHubs.process`
     - An `EventHubs.receive` span will be created upon receiving events.
     - Additional attributes added to spans:
       - `messaging.system` - messaging system (i.e., `eventhubs`)
       - `messaging.operation` - type of operation (i.e., `publish`, `receive`, or `process`)
       - `messaging.batch.message_count` - number of messages sent, received, or processed (if more than one)
     - The `component` attribute was removed from all spans.
     - All `send` spans now contain links to `message` spans. Now, `message` spans will no longer contain a link to the `send` span.
     - Message application properties will now contain values for `traceparent` (and `tracestate` if applicable)
     - Process spans will now be a direct children of message span contexts in when event handling on a per-message basis. ([#30537](https://github.com/Azure/azure-sdk-for-python/pull/30537))





  - Fixed a bug that would prevent reconnect after a long idle period, network drop (issue #28996)





  - Fixed a bug where, when `websocket-client` was not installed, the error was not caught/raised properly (issue #28453).



  Version 5.11.0 is our first stable release of the Azure Event Hubs client library based on a pure Python implemented AMQP stack.



  - A new boolean keyword argument `uamqp_transport` has been added to sync and async `EventHubProducerClient`/`EventHubConsumerClient` constructors which indicates whether to use the `uamqp` library or the default pure Python AMQP library as the underlying transport.



  - Fixed a bug that caused an error when sending batches with tracing enabled (issue #27986).
  - Fixed a bug where `EventHubSharedKeyCredential` returned an `AccessToken.token` of type `bytes` and not `str`, now matching the documentation.



  - The `message` attribute on `EventData`/`EventDataBatch`, which previously exposed the `uamqp.Message`, has been deprecated.
    - `LegacyMessage`/`LegacyBatchMessage` objects returned by the `message` attribute on `EventData`/`EventDataBatch` have been introduced to help facilitate the transition.
  - Removed uAMQP from required dependencies.
  - Adding `uamqp >= 1.6.3` as an optional dependency for use with the `uamqp_transport` keyword.
    - Added support for Python 3.11.





  - Updated the optional dependency for async transport using AMQP over WebSocket from `websocket-client` to `aiohttp` (Issue #24315, thanks @hansmbakker for the suggestion).



  This version and all future versions will require Python 3.7+. Python 3.6 is no longer supported.



  - Added the `uamqp_transport` optional parameter to the clients, to allow switching to the `uamqp` library as the transport.



  This version and all future versions will require Python 3.7+, Python 3.6 is no longer supported.



  - Fixed a bug in async `BufferedProducer` that would block when flushing the queue causing the client to freeze up (issue #23510).
  - Fixed a bug in the async `EventHubProducerClient` and `EventHubConsumerClient` that set the default value of the `transport_type` parameter in the `from_connection_string` methods to `None` rather than `TransportType.Amqp`.



  - Internal refactoring to support upcoming Pure Python AMQP-based release.
  - Updated uAMQP dependency to 1.6.0.





  - Fixed bug that prevented token refresh at regular intervals.
  - Fixed bug that was improperly passing the debug keyword argument, so that network trace debug logs are output when requested.



  - Added logging added in to track proper token refreshes & fetches, output exception reason for producer init failure.





  - Includes the following features related to buffered sending of events:
    - A new method `send_event` to `EventHubProducerClient` which allows sending single `EventData` or `AmqpAnnotatedMessage`.
    - Buffered mode sending to `EventHubProducerClient` which is intended to allow for efficient publishing of events
     without having to explicitly manage batches in the application.
      - The constructor of `EventHubProducerClient` and `from_connection_string` method takes the following new keyword arguments
       for configuration:
        - `buffered_mode`: The flag to enable/disable buffered mode sending.
        - `on_success`: The callback to be called once events have been successfully published.
        - `on_error`: The callback to be called once events have failed to be published.
        - `max_buffer_length`: The total number of events per partition that can be buffered before a flush will be triggered.
        - `max_wait_time`: The amount of time to wait for a batch to be built with events in the buffer before publishing.
      - A new method `EventHubProducerClient.flush` which flushes events in the buffer to be sent immediately.
      - A new method `EventHubProducerClient.get_buffered_event_count` which returns the number of events that are buffered and waiting to be published for a given partition.
      - A new property `EventHubProducerClient.total_buffered_event_count` which returns the total number of events that are currently buffered and waiting to be published, across all partitions.
      - A new boolean keyword argument `flush` to `EventHubProducerClient.close` which indicates whether to flush the buffer or not while closing.





  - Added support for connection using websocket and http proxy.
  - Added support for custom endpoint connection over websocket.





  - The classmethod `from_message_content` has been added to `EventData` for interoperability with the Schema Registry Avro Encoder library, and takes `content` and `content_type` as positional parameters.



  - Features related to buffered sending of events are still in beta and will not be included in this release.





  - Introduced new method `send_event` to `EventHubProducerClient` which allows sending single `EventData` or `AmqpAnnotatedMessage`.
  - Introduced buffered mode sending to `EventHubProducerClient` which is intended to allow for efficient publishing of events
   without having to explicitly manage batches in the application.
    - The constructor of `EventHubProducerClient` and `from_connection_string` method now takes the following new keyword arguments
     for configuration:
      - `buffered_mode`: The flag to enable/disable buffered mode sending.
      - `on_success`: The callback to be called once events have been successfully published.
      - `on_error`: The callback to be called once events have failed to be published.
      - `max_buffer_length`: The total number of events per partition that can be buffered before a flush will be triggered.
      - `max_wait_time`: The amount of time to wait for a batch to be built with events in the buffer before publishing.
    - Introduced new method `EventHubProducerClient.flush` which flushes events in the buffer to be sent immediately.
    - Introduced new method `EventHubProducerClient.get_buffered_event_count` which returns the number of events that are buffered and waiting to be published for a given partition.
    - Introduced new property `EventHubProducerClient.total_buffered_event_count` which returns the total number of events that are currently buffered and waiting to be published, across all partitions.
    - Introduced new boolean keyword argument `flush` to `EventHubProducerClient.close` which indicates whether to flush the buffer or not while closing.



  - Updated `EventData` internals for interoperability with the Schema Registry Avro Encoder library.





  - `from_message_data` on `EventData` has been renamed `from_message_content` for interoperability with the Schema Registry Avro Encoder library. The `data` parameter has been renamed to `content`.





  - Improved the performance of async sending and receiving.



  - The following features have been temporarily pulled out of async `EventHubProducerClient` and `EventHubConsumerClient` which will be added back in future previews as we work towards a stable release:
    - Passing the following keyword arguments to the constructors and `from_connection_string` methods of the `EventHubProducerClient` and `EventHubConsumerClient` is not supported:  `transport_type`, `http_proxy`, `custom_endpoint_address`, and `connection_verify`.





  - Added support for async `EventHubProducerClient` and `EventHubConsumerClient`.



  Version 5.8.0a1 is our first efforts to build an Azure Event Hubs client library based on pure python implemented AMQP stack.



  - The following features have been temporarily pulled out which will be added back in future previews as we work towards a stable release:
    - Async is not supported.
    - Passing the following keyword arguments to the constructors and `from_connection_string` methods of the `EventHubProducerClient` and `EventHubConsumerClient` is not supported:  `transport_type`, `http_proxy`, `custom_endpoint_address`, and `connection_verify`.



  - uAMQP dependency is removed.



  This version and all future versions will require Python 3.6+. Python 2.7 is no longer supported.



  - Added support for fixed (linear) retry backoff:
    - Sync/async `EventHubProducerClient` and `EventHubConsumerClient` constructors and `from_connection_string` take `retry_mode` as a keyword argument.



  - Fixed a bug that `EventHubProducerClient` could be reopened for sending events instead of encountering with `KeyError` when the client is previously closed (issue #21849).



  - Improved token refresh timing to prevent potentially blocking main flow when the token is about to get expired soon.
  - Updated uAMQP dependency to 1.5.1.





  - Fixed a bug for checking that `azure.eventhub.amqp.AmqpMessageHeader` and `azure.eventhub.amqp.AmqpMessageProperties` contain specific properties using the `in` keyword.



  - Updated uAMQP dependency to 1.4.3.
    - Added support for Python 3.10.
    - Fixed memory leak in win32 socketio and tlsio (issue #19777).
    - Fixed memory leak in the process of converting AMQPValue into string (issue #19777).





  - Added support for sending AMQP annotated message which allows full access to the AMQP message fields.
    - Introduced new namespace `azure.eventhub.amqp`.
    - Added new enum class `azure.eventhub.amqp.AmqpMessageBodyType` to represent the body type of the message which includes:
      - `DATA`: The body of message consists of one or more data sections and each section contains opaque binary data.
      - `SEQUENCE`: The body of message consists of one or more sequence sections and each section contains an arbitrary number of structured data elements.
      - `VALUE`: The body of message consists of one amqp-value section and the section contains a single AMQP value.
    - Introduced new class `azure.eventhub.amqp.AmqpAnnotatedMessage` for accessing low-level amqp message sections which can be instantiated for sending.
    - Introduced new classes `azure.eventhub.amqp.AmqpMessageHeader` and `azure.eventhub.amqp.AmqpMessageProperties` for accessing amqp header and properties.
    - Added new property `body_type` on `azure.eventhub.EventData` which returns `azure.eventhub.amqp.AmqpMessageBodyType`.
    - Added new read-only property `raw_amqp_message` on `azure.eventhub.EventData` which returns `azure.eventhub.amqp.AmqpAnnotatedMessage`.



  - Updated uAMQP dependency to 1.4.1.
    - Fixed a bug that attributes creation_time, absolute_expiry_time and group_sequence on MessageProperties should be compatible with integer types on Python 2.7.



  **New Features**

  - Added support for using `azure.core.credentials.AzureNamedKeyCredential` as credential for authenticating producer and consumer clients.

  **Bug Fixes**

  - Fixed bug that custom user agent string should be put in front of the built-in user agent string instead of being appended.
  - Updated uAMQP dependency to 1.4.0.
    - Fixed memory leaks in the process of link attach where source and target cython objects are not properly deallocated (#15747).
    - Improved management operation callback not to parse description value of non AMQP_TYPE_STRING type as string (#18361).

  **Notes**

  - Updated azure-core dependency to 1.14.0.



  This version follows from version 5.3.1, rather than 5.4.0b1 so that the preview idempotent producer feature is not included.

  **New Features**

  - Added support for using `azure.core.credentials.AzureSasCredential` as credential for authenticating producer and consumer clients.
  - Updated `list_ownership`, `claim_ownership`, `update_checkpoint`, `list_checkpoints` on sync and async `CheckpointStore` to support taking `**kwargs`.
    - WARNING: Implementing a custom checkpointstore that does not support taking `**kwargs` in the methods listed previously will result in the following pylint error: `W0221: Parameters differ from overridden ________ method (arguments-differ)`.
  - Updated `update_checkpoint` on sync and async `PartitionContext` to support taking `**kwargs`.

  **Bug Fixes**

  - Updated uAMQP dependency to 1.3.0.
    - Fixed bug that sending message of large size triggering segmentation fault when the underlying socket connection is lost (#13739, #14543).
    - Fixed bug in link flow control where link credit and delivery count should be calculated based on per message instead of per transfer frame (#16934).

  **Notes**

  - Updated azure-core dependency to 1.13.0.



  This version and all future versions will require Python 2.7 or Python 3.6+, Python 3.5 is no longer supported.

  **New Features**

  - Added support for idempotent publishing which is supported by the service to endeavor to reduce the number of duplicate
    events that are published.
    - `EventHubProducerClient` constructor accepts two new parameters for idempotent publishing:
      - `enable_idempotent_partitions`: A boolean value to tell the `EventHubProducerClient` whether to enable idempotency.
      - `partition_config`: The set of configurations that can be specified to influence publishing behavior
       specific to the configured Event Hub partition.
    - Introduced a new method `get_partition_publishing_properties` on `EventHubProducerClient` to inspect the information
      about the state of publishing for a partition.
    - Introduced a new property `published_sequence_number` on `EventData` to get the publishing sequence number assigned
      to the event at the time it was successfully published.
    - Introduced a new property `starting_published_sequence_number` on `EventDataBatch` to get the publishing sequence
      number assigned to the first event in the batch at the time the batch was successfully published.
    - Introduced a new class `azure.eventhub.PartitionPublishingConfiguration` which is a set of configurations that can be
      specified to influence the behavior when publishing directly to an Event Hub partition.

  **Notes**

  - Updated uAMQP dependency to 1.2.15.



  This version will be the last version to officially support Python 3.5, future versions will require Python 2.7 or Python 3.6+.

  **Bug fixes**

  - Sending empty `event_data_batch` will be a no-op now instead of raising error.



  **New Features**

  - Added a `parse_connection_string` method which parses a connection string into a properties bag, `EventHubConnectionStringProperties`, containing its component parts.
  - The constructor and `from_connection_string` method of `EventHubConsumerClient` and `EventHubProducerClient` now accept two new optional arguments:
    - `custom_endpoint_address` which allows for specifying a custom endpoint to use when communicating with the Event Hubs service,
  and is useful when your network does not allow communicating to the standard Event Hubs endpoint.
    - `connection_verify` which allows for specifying the path to the custom CA_BUNDLE file of the SSL certificate which is used to authenticate
  the identity of the connection endpoint.

  **Notes**

  - Updated uAMQP dependency to 1.2.14.



  **Bug fixes**

  - Updated `azure.eventhub.extension.__init__.py` to be compatible with pkgutil-style namespace (PR #13210, thanks @pjachowi).
  - Updated uAMQP dependency to 1.2.13
    - Added support for Python 3.9.
    - Fixed bug that macOS was unable to detect network error (#15473).
    - Fixed bug that `uamqp.ReceiveClient` and `uamqp.ReceiveClientAsync` receive messages during connection establishment (#15555).
    - Fixed bug where connection establishment on macOS with Clang 12 triggering unrecognized selector exception (#15567).
    - Fixed bug in accessing message properties triggering segmentation fault when the underlying C bytes are NULL (#15568).



  **New Features**

  - Connection strings used with `from_connection_string` methods now supports using the `SharedAccessSignature` key in leiu of `sharedaccesskey` and `sharedaccesskeyname`, taking the string of the properly constructed token as value.



  **New Features**

  - `EventHubConsumerClient` constructor accepts two new parameters for the load balancer.
      - `load_balancing_strategy`, which can be "greedy" or "balanced".
       With greedy strategy, one execution of load balancing will claim as many partitions as required to balance the load
       whereas with balanced strategy one execution of load balancing will claim at most 1 partition.
      - `partition_ownership_expiration_interval`, which allows you to customize the partition ownership expiration for load balancing.
       A consumer client may lose its owned partitions more often with a smaller expiration interval. But a larger interval
       may result in idle partitions not being claimed for longer time.
  - Added enum class `azure.eventhub.LoadBalancingStrategy` for `load_balancing_strategy`.



  **New Features**

  - `EventHubProducerClient.send_batch` accepts either an `EventDataBatch` or a finite list of `EventData`. #9181
  - Added enqueueTime to span links of distributed tracing. #9599

  **Bug fixes**

  - Fixed a bug that turned `azure.eventhub.EventhubConsumerClient` into an exclusive receiver when it has no checkpoint store. #11181
  - Updated uAMQP dependency to 1.2.7.
    - Fixed bug in setting certificate of tlsio on MacOS. #7201
    - Fixed bug that caused segmentation fault in network tracing on MacOS when setting `logging_enable` to `True` in `EventHubConsumerClient` and `EventHubProducerClient`.



  **New Features**

  - Added `EventHubConsumerClient.receive_batch()` to receive and process events in batches instead of one by one. #9184
  - `EventHubConsumerCliuent.receive()` has a new param `max_wait_time`.
  `on_event` is called every `max_wait_time` when no events are received and `max_wait_time` is not `None` or 0.
  - Param event of `PartitionContext.update_checkpoint` is now optional. The last received event is used when param event is not passed in.
  - `EventData.system_properties` has added missing properties when consuming messages from IotHub. #10408



  **Bug fixes**

  - Fixed a bug that swallowed errors when receiving events with `azure.eventhub.EventHubConsumerClient`  #9660
  - Fixed a bug that caused `get_eventhub_properties`, `get_partition_ids`, and `get_partition_properties` to raise
  an error on Azure Stack #9920



  **Breaking changes**

  - `EventData`
      - Removed deprecated property `application_properties` and deprecated method `encode_message()`.
  - `EventHubConsumerClient`
      - `on_error` would be called when `EventHubConsumerClient` failed to claim ownership of partitions.
      - `on_partition_close` and `on_partition_initialize` would be called in the case of exceptions raised by `on_event` callback.
          -  `EventHubConsumerClient` would close and re-open the internal partition receiver in this case.
      - Default starting position from where `EventHubConsumerClient` should resume receiving after recovering from an error has been re-prioritized.
          - If there is checkpoint, it will resume from the checkpoint.
          - If there is no checkpoint but `starting_position` is provided, it will resume from `starting_posititon`.
          - If there is no checkpoint or `starting_position`, it will resume from the latest position.
  - `PartitionContext`
      - `update_checkpoint` would do in-memory checkpoint instead of doing nothing when checkpoint store is not explicitly provided.
          - The in-memory checkpoints would be used for `EventHubConsumerClient` receiving recovering.
  - `get_partition_ids`, `get_partition_properties`, `get_eventhub_properties` would raise error in the case of service returning an error status code.
      - `AuthenticationError` would be raised when service returning error code 401.
      - `ConnectError` would be raised when service returning error code 404.
      - `EventHubError` would be raised when service returning other error codes.



  **Breaking changes**

  - All exceptions should now be imported from `azure.eventhub.exceptions`.
  - Introduced separate `EventHubSharedKeyCredential` objects for synchronous and asynchronous operations.
    For async, import the credentials object from the `azure.eventhub.aio` namespace.
  - `EventData`
      - Renamed property `application_properties` to `properties`.
      - `EventData` no longer has attribute `last_enqueued_event_properties` - use this on `PartitionContext` instead.
  - `EvenDataBatch`
      - `EventDataBatch.try_add` has been renamed to `EventDataBatch.add`.
      - Renamed property `size` to `size_in_bytes`.
      - Renamed attribute `max_size` to `max_size_in_bytes`.
  - `EventHubConsumerClient` and `EventHubProducerClient`
      - Renamed method `get_properties` to `get_eventhub_properties`.
      - Renamed parameters in constructor: `host` to `fully_qualified_namespace`, `event_hub_path` to `eventhub_name`.
      - Renamed parameters in `get_partition_properties`: `partition` to `partition_id`.
      - Renamed parameter `consumer_group_name` to `consumer_group` and moved that parameter from `receive` method to the constructor of `EventHubConsumerClient`.
      - Renamed parameter `initial_event_position` to `starting_position` on the `receive` method of `EventHubConsumerClient`.
      - Renamed parameter `event_hub_path` to `eventhub_name` in constructor and `from_connection_string` method of the client object.
      - `EventHubProducerClient.send` has been renamed to `send_batch` which will only accept `EventDataBatch` object as input.
      - `EventHubProducerClient.create_batch` now also takes the `partition_id` and `partition_key` as optional parameters (which are no longer specified at send).
  - Renamed module `PartitionManager` to `CheckpointStore`.
  - Receive event callback parameter has been renamed to `on_event` and now operates on a single event rather than a list of events.
  - Removed class `EventPostition`.
      - The `starting_position` parameter of the `receive` method accepts offset(`str`), sequence number(`int`), datetime (`datetime.datetime`) or `dict` of these types.
      - The `starting_position_inclusive` parameter of the `receive` method accepts `bool` or `dict` indicating whether the given event position is inclusive or not.
  - `PartitionContext` no longer has attribute `owner_id`.
  - `PartitionContext` now has attribute `last_enqueued_event_properties` which is populated if `track_last_enqueued_event_properties` is set to `True` in the `receive` method.

  **New features**

  - Added new parameter `idle_timeout` in construct and `from_connection_string` to `EventHubConsumerClient` and `EventHubProducerClient`
  after which the underlying connection will close if there is no further activity.



  **Breaking changes**

  - `EventHubClient`, `EventHubConsumer` and `EventHubProducer` has been removed. Use `EventHubProducerClient` and `EventHubConsumerClient` instead.
      - Construction of both objects is the same as it was for the previous client.
  - Introduced `EventHubProducerClient` as substitution for`EventHubProducer`.
      - `EventHubProducerClient` supports sending events to different partitions.
  - Introduced `EventHubConsumerClient` as substitution for `EventHubConsumer`.
      - `EventHubConsumerClient` supports receiving events from single/all partitions.
      - There are no longer methods which directly return `EventData`, all receiving is done via callback method: `on_events`.
  - `EventHubConsumerClient` has taken on the responsibility of `EventProcessor`.
      - `EventHubConsumerClient` now accepts `PartitionManager` to do load-balancing and checkpoint.
  - Replaced `PartitionProcessor`by four independent callback methods accepted by the `receive` method on `EventHubConsumerClient`.
      - `on_events(partition_context, events)` called when events are received.
      - `on_error(partition_context, exception` called when errors occur.
      - `on_partition_initialize(partition_context)` called when a partition consumer is opened.
      - `on_partition_close(partition_context, reason)` called when a partition consumer is closed.
  - Some modules and classes that were importable from several different places have been removed:
      - `azure.eventhub.common` has been removed. Import from `azure.eventhub` instead.
      - `azure.eventhub.client_abstract` has been removed. Use `azure.eventhub.EventHubProducerClient` or `azure.eventhub.EventHubConsumerClient` instead.
      - `azure.eventhub.client` has been removed. Use `azure.eventhub.EventHubProducerClient` or `azure.eventhub.EventHubConsumerClient` instead.
      - `azure.eventhub.producer` has been removed. Use `azure.eventhub.EventHubProducerClient` instead.
      - `azure.eventhub.consumer` has been removed. Use `azure.eventhub.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.client_async` has been removed. Use `azure.eventhub.aio.EventHubProducerClient` or `azure.eventhub.aio.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.producer_async` has been removed. Use `azure.eventhub.aio.EventHubProducerClient` instead.
      - `azure.eventhub.aio.consumer_async` has been removed. Use `azure.eventhub.aio.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.event_processor.event_processor` has been removed. Use `azure.eventhub.aio.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.event_processor.partition_processor` has been removed. Use callback methods instead.
      - `azure.eventhub.aio.event_processor.partition_manager` has been removed. Import from `azure.eventhub.aio` instead.
      - `azure.eventhub.aio.event_processor.partition_context` has been removed. Import from `azure.eventhub.aio` instead.
      - `azure.eventhub.aio.event_processor.sample_partition_manager` has been removed.

  **Bug fixes**

  - Fixed bug in user-agent string not being parsed.



  **New features**

  - Added support for tracing (issue #7153).
  - Added the capability of tracking last enqueued event properties of the partition to `EventHubConsumer` .
      - Added new boolean type parameter`track_last_enqueued_event_properties` in method `EventHubClient.create_consumer()`.
      - Added new property `last_enqueued_event_properties` of `EventHubConsumer` which contains sequence_number, offset, enqueued_time and retrieval_time information.
      - By default the capability is disabled as it will cost extra bandwidth for transferring more information if turned on.

  **Breaking changes**

  - Removed support for IoT Hub direct connection.
      - [EventHubs compatible connection string](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messages-read-builtin) of an IotHub can be used to create `EventHubClient` and read properties or events from an IoT Hub.
  - Removed support for sending EventData to IoT Hub.
  - Removed parameter `exception` in method `close()` of `EventHubConsumer` and `EventHubProcuer`.
  - Updated uAMQP dependency to 1.2.3.



  **New features**

  - Added support for automatic load balancing among multiple `EventProcessor`.
  - Added `BlobPartitionManager` which implements `PartitionManager`.
      - Azure Blob Storage is applied for storing data used by `EventProcessor`.
      - Packaged separately as a plug-in to `EventProcessor`.
      - For details, please refer to [Azure Blob Storage Partition Manager](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventhub/azure-eventhub-checkpointstoreblob-aio).
  - Added property `system_properties` on `EventData`.

  **Breaking changes**

  - Removed constructor method of `PartitionProcessor`. For initialization please implement the method `initialize`.
  - Replaced `CheckpointManager` by `PartitionContext`.
      - `PartitionContext` has partition context information and method `update_checkpoint`.
  - Updated all methods of `PartitionProcessor` to include `PartitionContext` as part of the arguments.
  - Updated accessibility of class members in `EventHub/EventHubConsumer/EventHubProducer`to be private.
  - Moved `azure.eventhub.eventprocessor` under `aio` package, which now becomes `azure.eventhub.aio.eventprocessor`.



  **New features**

  - Added method `create_batch` on the `EventHubProducer` to create an `EventDataBatch` that can then be used to add events until the maximum size is reached.
      - This batch object can then be used in the `send()` method to send all the added events to Event Hubs.
      - This allows publishers to build batches without the possibility of encountering the error around the message size exceeding the supported limit when sending events.
      - It also allows publishers with bandwidth concerns to control the size of each batch published.
  - Added new configuration parameters for exponential delay between retry operations.
      - `retry_total`: The total number of attempts to redo the failed operation.
      - `backoff_factor`: The delay time factor.
      - `backoff_max`: The maximum delay time in total.
  - Added support for context manager on `EventHubClient`.
  - Added new error type `OperationTimeoutError` for send operation.
  - Introduced a new class `EventProcessor` which replaces the older concept of [Event Processor Host](https://docs.microsoft.com/azure/event-hubs/event-hubs-event-processor-host). This early preview is intended to allow users to test the new design using a single instance of `EventProcessor`. The ability to checkpoints to a durable store will be added in future updates.
      - `EventProcessor`: EventProcessor creates and runs consumers for all partitions of the eventhub.
      - `PartitionManager`: PartitionManager defines the interface for getting/claiming ownerships of partitions and updating checkpoints.
      - `PartitionProcessor`: PartitionProcessor defines the interface for processing events.
      - `CheckpointManager`: CheckpointManager takes responsibility for updating checkpoints during events processing.

  **Breaking changes**

  - `EventProcessorHost` was replaced by `EventProcessor`, please read the new features for details.
  - Replaced `max_retries` configuration parameter of the EventHubClient with `retry_total`.




  Version 5.0.0b1 is a preview of our efforts to create a client library that is user friendly and idiomatic to the Python ecosystem. The reasons for most of the changes in this update can be found in the [Azure SDK Design Guidelines for Python](https://azuresdkspecs.z5.web.core.windows.net/PythonSpec.html). For more information, please visit https://aka.ms/azure-sdk-preview1-python.

  **New features**

  - Added new configuration parameters for creating EventHubClient.
    - `credential`: The credential object used for authentication which implements `TokenCredential` interface of getting tokens.
    - `transport_type`: The type of transport protocol that will be used for communicating with the Event Hubs service.
    - `max_retries`: The max number of attempts to redo the failed operation when an error happened.
    - for detailed information about the configuration parameters, please read the reference documentation.
  - Added new methods `get_partition_properties` and `get_partition_ids` to EventHubClient.
  - Added support for http proxy.
  - Added support for authentication using azure-identity credential.
  - Added support for transport using AMQP over WebSocket.

  **Breaking changes**

  - New error hierarchy
    - `azure.error.EventHubError`
    - `azure.error.ConnectionLostError`
    - `azure.error.ConnectError`
    - `azure.error.AuthenticationError`
    - `azure.error.EventDataError`
    - `azure.error.EventDataSendError`
  - Renamed Sender/Receiver to EventHubProducer/EventHubConsumer.
    - Renamed `add_sender` to `create_producer` and `add_receiver` to `create_consumer` in EventHubClient.
    - EventHubConsumer is now iterable.
  - Rename class azure.eventhub.Offset to azure.eventhub.EventPosition.
  - Rename method `get_eventhub_info` to `get_properties` of EventHubClient.
  - Reorganized connection management, EventHubClient is no longer responsible for opening/closing EventHubProducer/EventHubConsumer.
    - Each EventHubProducer/EventHubConsumer is responsible for its own connection management.
    - Added support for context manager on EventHubProducer and EventHubConsumer.
  - Reorganized async APIs into "azure.eventhub.aio" namespace and rename to drop the "_async" suffix.
  - Updated uAMQP dependency to 1.2.



  **BugFixes**

  - Fixed bug where datetime offset filter was using a local timestamp rather than UTC.
  - Fixed stackoverflow error in continuous connection reconnect attempts.




  **BugFixes**

  - Added support for auto reconnect on token expiration and other auth errors (issue #89).

  **Features**

  - Added ability to create ServiceBusClient from an existing SAS auth token, including
    providing a function to auto-renew that token on expiry.
  - Added support for storing a custom EPH context value in checkpoint (PR #84, thanks @konstantinmiller)




  - Support for Python 2.7 in azure.eventhub module (azure.eventprocessorhost will not support Python 2.7).
  - Parse EventData.enqueued_time as a UTC timestamp (issue #72, thanks @vjrantal)




  - Fixed bug in Azure namespace package.




  - Changes to `AzureStorageCheckpointLeaseManager` parameters to support other connection options (issue #61):
    - The `storage_account_name`, `storage_account_key` and `lease_container_name` arguments are now optional keyword arguments.
    - Added a `sas_token` argument that must be specified with `storage_account_name` in place of `storage_account_key`.
    - Added an `endpoint_suffix` argument to support storage endpoints in National Clouds.
    - Added a `connection_string` argument that, if specified, overrides all other endpoint arguments.
    - The `lease_container_name` argument now defaults to `"eph-leases"` if not specified.

  - Fix for clients failing to start if run called multipled times (issue #64).
  - Added convenience methods `body_as_str` and `body_as_json` to EventData object for easier processing of message data.




  - API stable.
  - Renamed internal `_async` module to `async_ops` for docs generation.
  - Added optional `auth_timeout` parameter to `EventHubClient` and `EventHubClientAsync` to configure how long to allow for token
    negotiation to complete. Default is 60 seconds.
  - Added optional `send_timeout` parameter to `EventHubClient.add_sender` and `EventHubClientAsync.add_async_sender` to determine the
    timeout for Events to be successfully sent. Default value is 60 seconds.
  - Reformatted logging for performance.




  - Stability improvements for EPH.
  - Updated uAMQP version.
  - Added new configuration options for Sender and Receiver; `keep_alive` and `auto_reconnect`.
    These flags have been added to the following:

    - `EventHubClient.add_receiver`
    - `EventHubClient.add_sender`
    - `EventHubClientAsync.add_async_receiver`
    - `EventHubClientAsync.add_async_sender`
    - `EPHOptions.keey_alive_interval`
    - `EPHOptions.auto_reconnect_on_error`




  - **Breaking change** `EventData.offset` will now return an object of type `~uamqp.common.Offset` rather than str.
    The original string value can be retrieved from `~uamqp.common.Offset.value`.
  - Each sender/receiver will now run in its own independent connection.
  - Updated uAMQP dependency to 0.2.0
  - Fixed issue with IoTHub clients not being able to retrieve partition information.
  - Added support for HTTP proxy settings to both EventHubClient and EPH.
  - Added error handling policy to automatically reconnect on retryable error.
  - Added keep-alive thread for maintaining an unused connection.




  - **Breaking change** Restructured library to support Python 3.7. Submodule `async` has been renamed and all classes from
    this module can now be imported from azure.eventhub directly.
  - **Breaking change** Removed optional `callback` argument from `Receiver.receive` and `AsyncReceiver.receive`.
  - **Breaking change** `EventData.properties` has been renamed to `EventData.application_properties`.
    This removes the potential for messages to be processed via callback for not yet returned
    in the batch.
  - Updated uAMQP dependency to v0.1.0
  - Added support for constructing IoTHub connections.
  - Fixed memory leak in receive operations.
  - Dropped Python 2.7 wheel support.




  - Added `namespace_suffix` to EventHubConfig() to support national clouds.
  - Added `device_id` attribute to EventData to support IoT Hub use cases.
  - Added message header to workaround service bug for PartitionKey support.
  - Updated uAMQP dependency to vRC1.




  - Updated uAMQP to latest version.
  - Further testing and minor bug fixes.




  - Updated uAQMP dependency.


pkgId: e199e00af137532f7b77509fc2bde4fa810f0bf9a77fe89a82a39f4464d50735
name: python-azure-eventhub
arch: src
version: 5.12.2
epoch: 0
release: 1
summary: Microsoft Azure Event Hubs Client Library for Python
url: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventhub/azure-eventhub
rpm_license: MIT License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-azure-eventhub-5.12.2-1.src.rpm
checksum_type: sha256
description:
  Azure Event Hubs is a highly scalable publish-subscribe service that can ingest millions of events per second and stream
  them to multiple consumers. This lets you process and analyze the massive amounts of data produced by your connected
  devices and applications. Once Event Hubs has collected the data, you can retrieve, transform, and store it by using
  any real-time analytics provider or with batching/storage adapters. If you would like to know more about Azure Event Hubs,
  you may wish to review: [What is Event Hubs](https://docs.microsoft.com/azure/event-hubs/event-hubs-about)?

  The Azure Event Hubs client library allows for publishing and consuming of Azure Event Hubs events and may be used to:

  - Emit telemetry about your application for business intelligence and diagnostic purposes.
  - Publish facts about the state of your application which interested parties may observe and use as a trigger for taking action.
  - Observe interesting operations and interactions happening within your business or other ecosystem, allowing loosely coupled systems to interact without the need to bind them together.
  - Receive events from one or more publishers, transform them to better meet the needs of your ecosystem, then publish the transformed events to a new stream for consumers to observe.

  [Source code](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/)
  | [Package (PyPi)](https://pypi.org/project/azure-eventhub/)
  | [Package (Conda)](https://anaconda.org/microsoft/azure-eventhub/)
  | [API reference documentation][api_reference]
  | [Product documentation](https://docs.microsoft.com/azure/event-hubs/)
  | [Samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventhub/azure-eventhub/samples)





  - Python 3.8 or later.
  - **Microsoft Azure Subscription:**  To use Azure services, including Azure Event Hubs, you'll need a subscription.
  If you do not have an existing Azure account, you may sign up for a free trial or use your MSDN subscriber benefits when you [create an account](https://azure.microsoft.com/free/).

  - **Event Hubs namespace with an Event Hub:** To interact with Azure Event Hubs, you'll also need to have a namespace and Event Hub  available.
  If you are not familiar with creating Azure resources, you may wish to follow the step-by-step guide
  for [creating an Event Hub using the Azure portal](https://docs.microsoft.com/azure/event-hubs/event-hubs-create).
  There, you can also find detailed instructions for using the Azure CLI, Azure PowerShell, or Azure Resource Manager (ARM) templates to create an Event Hub.



  Install the Azure Event Hubs client library for Python with pip:

  ```
  $ pip install azure-eventhub
  ```



  Interaction with Event Hubs starts with an instance of EventHubConsumerClient or EventHubProducerClient class. You need either the host name, SAS/AAD credential and event hub name or a connection string to instantiate the client object.

  **[Create client from connection string:](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples/sync_samples/connection_string_authentication.py)**

  For the Event Hubs client library to interact with an Event Hub, the easiest means is to use a connection string, which is created automatically when creating an Event Hubs namespace.
  If you aren't familiar with shared access policies in Azure, you may wish to follow the step-by-step guide to [get an Event Hubs connection string](https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string).

  - The `from_connection_string` method takes the connection string of the form
  `Endpoint=sb://<yournamespace>.servicebus.windows.net/;SharedAccessKeyName=<yoursharedaccesskeyname>;SharedAccessKey=<yoursharedaccesskey>` and
  entity name to your Event Hub instance. You can get the connection string from the [Azure portal](https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string#get-connection-string-from-the-portal).

  **[Create client using the azure-identity library:](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples/sync_samples/client_identity_authentication.py)**

  Alternately, one can use a Credential object to authenticate via AAD with the azure-identity package.

  - This constructor demonstrated in the sample linked above takes the host name and entity name of your Event Hub instance and credential that implements the
  [TokenCredential](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/azure/core/credentials.py)
  protocol. There are implementations of the `TokenCredential` protocol available in the
  [azure-identity package](https://pypi.org/project/azure-identity/). The host name is of the format `<yournamespace.servicebus.windows.net>`.
  - To use the credential types provided by `azure-identity`, please install the package:
  ```pip install azure-identity```
  - Additionally, to use the async API,  you must first install an async transport, such as [`aiohttp`](https://pypi.org/project/aiohttp/):
  ```pip install aiohttp```
  - When using Azure Active Directory, your principal must be assigned a role which allows access to Event Hubs, such as the
  Azure Event Hubs Data Owner role. For more information about using Azure Active Directory authorization with Event Hubs,
  please refer to [the associated documentation](https://docs.microsoft.com/azure/event-hubs/authorize-access-azure-active-directory).



  - An **EventHubProducerClient** is a source of telemetry data, diagnostics information, usage logs, or other log data,
  as part of an embedded device solution, a mobile device application, a game title running on a console or other device,
  some client or server based business solution, or a web site.

  - An **EventHubConsumerClient** picks up such information from the Event Hub and processes it. Processing may involve aggregation,
  complex computation, and filtering. Processing may also involve distribution or storage of the information in a raw or transformed fashion.
  Event Hub consumers are often robust and high-scale platform infrastructure parts with built-in analytics capabilities,
  like Azure Stream Analytics, Apache Spark, or Apache Storm.

  - A **partition** is an ordered sequence of events that is held in an Event Hub. Azure Event Hubs provides message streaming
  through a partitioned consumer pattern in which each consumer only reads a specific subset, or partition, of the message stream.
  As newer events arrive, they are added to the end of this sequence. The number of partitions is specified at the time an Event Hub is created and cannot be changed.

  - A **consumer group** is a view of an entire Event Hub. Consumer groups enable multiple consuming applications to each
  have a separate view of the event stream, and to read the stream independently at their own pace and from their own position.
  There can be at most 5 concurrent readers on a partition per consumer group; however it is recommended that there is only
  one active consumer for a given partition and consumer group pairing. Each active reader receives all of the events from
  its partition; if there are multiple readers on the same partition, then they will receive duplicate events.

  For more concepts and deeper discussion, see: [Event Hubs Features](https://docs.microsoft.com/azure/event-hubs/event-hubs-features).
  Also, the concepts for AMQP are well documented in [OASIS Advanced Messaging Queuing Protocol (AMQP) Version 1.0](https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-overview-v1.0-os.html).



  We do not guarantee that the EventHubProducerClient or EventHubConsumerClient are thread-safe. We do not recommend reusing these instances across threads. It is up to the running application to use these classes in a thread-safe manner.

  The data model type, `EventDataBatch` is not thread-safe. It should not be shared across threads nor used concurrently with client methods.



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

  - [Inspect an Event Hub](#inspect-an-event-hub)
  - [Publish events to an Event Hub](#publish-events-to-an-event-hub)
  - [Consume events from an Event Hub](#consume-events-from-an-event-hub)
  - [Consume events from an Event Hub in batches](#consume-events-from-an-event-hub-in-batches)
  - [Publish events to an Event Hub asynchronously](#publish-events-to-an-event-hub-asynchronously)
  - [Consume events from an Event Hub asynchronously](#consume-events-from-an-event-hub-asynchronously)
  - [Consume events from an Event Hub in batches asynchronously](#consume-events-from-an-event-hub-in-batches-asynchronously)
  - [Consume events and save checkpoints using a checkpoint store](#consume-events-and-save-checkpoints-using-a-checkpoint-store)
  - [Use EventHubConsumerClient to work with IoT Hub](#use-eventhubconsumerclient-to-work-with-iot-hub)



  Get the partition ids of an Event Hub.

  ```python
  import os
  from azure.eventhub import EventHubConsumerClient
  from azure.identity import DefaultAzureCredential

  FULLY_QUALIFIED_NAMESPACE = os.environ["EVENT_HUB_HOSTNAME"]
  EVENTHUB_NAME = os.environ['EVENT_HUB_NAME']

  consumer_client = EventHubConsumerClient(
      fully_qualified_namespace=FULLY_QUALIFIED_NAMESPACE,
      consumer_group='$Default',
      eventhub_name=EVENTHUB_NAME,
      credential=DefaultAzureCredential(),
  )

  with consumer_client:
      pass # consumer_client is now ready to be used.
  ```



  Use the `create_batch` method on `EventHubProducerClient` to create an `EventDataBatch` object which can then be sent using the `send_batch` method.
  Events may be added to the `EventDataBatch` using the `add` method until the maximum batch size limit in bytes has been reached.

  <!-- SNIPPET:send.send_event_data_batch -->

  ```python
  def send_event_data_batch(producer):
      
      
      event_data_batch = producer.create_batch()
      event_data_batch.add(EventData('Single message'))
      producer.send_batch(event_data_batch)
  ```

  <!-- END SNIPPET -->



  There are multiple ways to consume events from an EventHub.  To simply trigger a callback when an event is received,
  the `EventHubConsumerClient.receive` method will be of use as follows:

  ```python
  import logging
  from azure.eventhub import EventHubConsumerClient
  from azure.identity import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'
  client = EventHubConsumerClient(
      fully_qualified_namespace=fully_qualified_namespace,
      eventhub_name=eventhub_name,
      consumer_group=consumer_group,
      credential=DefaultAzureCredential(),
  )

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  def on_event(partition_context, event):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      partition_context.update_checkpoint(event)

  with client:
      client.receive(
          on_event=on_event,
          starting_position="-1",  # "-1" is from the beginning of the partition.
      )
      
      
  ```



  Whereas the above sample triggers the callback for each message as it is received, the following sample
  triggers the callback on a batch of events, attempting to receive a number at a time.

  ```python
  import logging
  from azure.eventhub import EventHubConsumerClient
  from azure.identity import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'
  client = EventHubConsumerClient(
      fully_qualified_namespace=fully_qualified_namespace,
      eventhub_name=eventhub_name,
      consumer_group=consumer_group,
      credential=DefaultAzureCredential(),
  )

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  def on_event_batch(partition_context, events):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      partition_context.update_checkpoint()

  with client:
      client.receive_batch(
          on_event_batch=on_event_batch,
          starting_position="-1",  # "-1" is from the beginning of the partition.
      )
      
      
  ```



  Use the `create_batch` method on `EventHubProducer` to create an `EventDataBatch` object which can then be sent using the `send_batch` method.
  Events may be added to the `EventDataBatch` using the `add` method until the maximum batch size limit in bytes has been reached.
  ```python
  import asyncio
  from azure.eventhub.aio import EventHubProducerClient   # The package name suffixed with ".aio" for async
  from azure.eventhub import EventData
  from azure.identity.aio import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  async def create_batch(client):
      event_data_batch = await client.create_batch()
      can_add = True
      while can_add:
          try:
              event_data_batch.add(EventData('Message inside EventBatchData'))
          except ValueError:
              can_add = False  # EventDataBatch object reaches max_size.
      return event_data_batch

  async def send():
      client = EventHubProducerClient(
          fully_qualified_namespace=fully_qualified_namespace,
          eventhub_name=eventhub_name,
          credential=DefaultAzureCredential(),
      )
      batch_data = await create_batch(client)
      async with client:
          await client.send_batch(batch_data)

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(send())
  ```



  This SDK supports both synchronous and asyncio based code.  To receive as demonstrated in the samples above, but within
  aio, one would need the following:

  ```python
  import logging
  import asyncio
  from azure.eventhub.aio import EventHubConsumerClient
  from azure.identity.aio import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  async def on_event(partition_context, event):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      await partition_context.update_checkpoint(event)

  async def receive():
      client = EventHubConsumerClient(
          fully_qualified_namespace=fully_qualified_namespace,
          eventhub_name=eventhub_name,
          consumer_group=consumer_group,
          credential=DefaultAzureCredential(),
      )
      async with client:
          await client.receive(
              on_event=on_event,
              starting_position="-1",  # "-1" is from the beginning of the partition.
          )
          
          

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(receive())
  ```



  All synchronous functions are supported in aio as well.  As demonstrated above for synchronous batch receipt, one can accomplish
  the same within asyncio as follows:

  ```python
  import logging
  import asyncio
  from azure.eventhub.aio import EventHubConsumerClient
  from azure.identity.aio import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  logger = logging.getLogger("azure.eventhub")
  logging.basicConfig(level=logging.INFO)

  async def on_event_batch(partition_context, events):
      logger.info("Received event from partition {}".format(partition_context.partition_id))
      await partition_context.update_checkpoint()

  async def receive_batch():
      client = EventHubConsumerClient(
          fully_qualified_namespace=fully_qualified_namespace,
          eventhub_name=eventhub_name,
          consumer_group=consumer_group,
          credential=DefaultAzureCredential(),
      )
      async with client:
          await client.receive_batch(
              on_event_batch=on_event_batch,
              starting_position="-1",  # "-1" is from the beginning of the partition.
          )
          
          

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(receive_batch())
  ```



  `EventHubConsumerClient` is a high level construct which allows you to receive events from multiple partitions at once
  and load balance with other consumers using the same Event Hub and consumer group.

  This also allows the user to track progress when events are processed using checkpoints.

  A checkpoint is meant to represent the last successfully processed event by the user from a particular partition of
  a consumer group in an Event Hub instance. The `EventHubConsumerClient` uses an instance of `CheckpointStore` to update checkpoints
  and to store the relevant information required by the load balancing algorithm.

  Search pypi with the prefix `azure-eventhub-checkpointstore` to
  find packages that support this and use the `CheckpointStore` implementation from one such package. Please note that both sync and async libraries are provided.

  In the below example, we create an instance of `EventHubConsumerClient` and use a `BlobCheckpointStore`. You need
  to [create an Azure Storage account](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal)
  and a [Blob Container](https://docs.microsoft.com/azure/storage/blobs/storage-quickstart-blobs-portal#create-a-container) to run the code.

  [Azure Blob Storage Checkpoint Store Async](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub-checkpointstoreblob-aio)
  and [Azure Blob Storage Checkpoint Store Sync](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub-checkpointstoreblob)
  are one of the `CheckpointStore` implementations we provide that applies Azure Blob Storage as the persistent store.


  ```python
  import asyncio

  from azure.eventhub.aio import EventHubConsumerClient
  from azure.eventhub.extensions.checkpointstoreblobaio import BlobCheckpointStore
  from azure.identity.aio import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'
  blob_account_url = '<< STORAGE ACCOUNT URL >>'
  container_name = '<<NAME OF THE BLOB CONTAINER>>'

  async def on_event(partition_context, event):
      
      await partition_context.update_checkpoint(event)  # Or update_checkpoint every N events for better performance.

  async def receive(client):
      await client.receive(
          on_event=on_event,
          starting_position="-1",  # "-1" is from the beginning of the partition.
      )

  async def main():
      checkpoint_store = BlobCheckpointStore(
          blob_account_url=blob_account_url,
          container_name=container_name,
          credential=DefaultAzureCredential()
      )
      client = EventHubConsumerClient(
          fully_qualified_namespace=fully_qualified_namespace,
          eventhub_name=eventhub_name,
          credential=DefaultAzureCredential(),
          consumer_group=consumer_group,
          checkpoint_store=checkpoint_store,  # For load balancing and checkpoint. Leave None for no load balancing
      )
      async with client:
          await receive(client)

  if __name__ == '__main__':
      loop = asyncio.get_event_loop()
      loop.run_until_complete(main())
  ```



  You can use `EventHubConsumerClient` to work with IoT Hub as well. This is useful for receiving telemetry data of IoT Hub from the
  linked EventHub. The associated connection string will not have send claims, hence sending events is not possible.

  Please notice that the connection string needs to be for an [Event Hub-compatible endpoint](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messages-read-builtin),
  e.g. "Endpoint=sb://my-iothub-namespace-[uid].servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-iot-hub-name"

  There are two ways to get the Event Hubs compatible endpoint:
  - Manually get the "Built-in endpoints" of the IoT Hub in Azure Portal and receive from it.
  ```python
  from azure.eventhub import EventHubConsumerClient

  connection_str = 'Endpoint=sb://my-iothub-namespace-[uid].servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-iot-hub-name'
  consumer_group = '<< CONSUMER GROUP >>'
  client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group)

  partition_ids = client.get_partition_ids()
  ```
  - Programmatically retrieve the built-in Event Hubs compatible endpoint.
  Refer to [IoT Hub Connection String Sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples/async_samples/iot_hub_connection_string_receive_async.py).



  See the `azure-eventhub` [troubleshooting guide](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/TROUBLESHOOTING.md) for details on how to diagnose various failure scenarios.



  - Enable `azure.eventhub` logger to collect traces from the library.
  - Enable AMQP frame level trace by setting `logging_enable=True` when creating the client.
  - Refer to [this guide](https://learn.microsoft.com/azure/developer/python/sdk/azure-sdk-logging) on configuring logging for Azure libraries for Python for additional information.

  ```python
  import logging
  import sys

  handler = logging.StreamHandler(stream=sys.stdout)
  logger = logging.getLogger('azure.eventhub')
  logger.setLevel(logging.DEBUG)
  logger.addHandler(handler)

  ...

  from azure.eventhub import EventHubProducerClient, EventHubConsumerClient

  producer = EventHubProducerClient(..., logging_enable=True)
  consumer = EventHubConsumerClient(..., logging_enable=True)
  ```





  Please take a look at the [samples](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventhub/azure-eventhub/samples) directory for detailed examples of how to use this library to send and receive events to/from Event Hubs.



  Reference documentation is available [here](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-eventhub/latest/azure.eventhub.html).



  The EventHubs SDK integrates nicely with the [Schema Registry][schemaregistry_service] service and [Avro][avro].
  For more information, please refer to [Schema Registry SDK][schemaregistry_repo] and [Schema Registry Avro Encoder SDK][schemaregistry_avroencoder_repo].



  The Azure Event Hubs client library is now based on a pure Python AMQP implementation. `uAMQP` has been removed as required dependency.

  To use `uAMQP` as the underlying transport:

  1. Install `uamqp` with pip.

  ```
  $ pip install uamqp
  ```

  2. Pass `uamqp_transport=True` during client construction.

  ```python
  from azure.eventhub import EventHubProducerClient, EventHubConsumerClient
  from azure.identity import DefaultAzureCredential

  fully_qualified_namespace = '<< EVENT HUBS FULLY QUALIFIED NAMESPACE >>'
  consumer_group = '<< CONSUMER GROUP >>'
  eventhub_name = '<< NAME OF THE EVENT HUB >>'

  client = EventHubProducerClient(
      fully_qualified_namespace=fully_qualified_namespace,
      eventhub_name=eventhub_name,
      credential=DefaultAzureCredential(),
      uamqp_transport=True
  )
  client = EventHubConsumerClient(
      fully_qualified_namespace=fully_qualified_namespace,
      eventhub_name=eventhub_name,
      credential=DefaultAzureCredential(),
      consumer_group=consumer_group,
      uamqp_transport=True
  )
  ```

  Note: The `message` attribute on `EventData`/`EventDataBatch`, which previously exposed the `uamqp.Message`, has been deprecated.
   The "Legacy" objects returned by `EventData.message`/`EventDataBatch.message` have been introduced to help facilitate the transition.



  If [uAMQP](https://pypi.org/project/uamqp/) is intended to be used as the underlying AMQP protocol implementation for `azure-eventhub`,
  uAMQP wheels can be found for most major operating systems.

  If you intend to use `uAMQP` and you're running on a platform for which uAMQP wheels are not provided, please follow
   the [uAMQP Installation](https://github.com/Azure/azure-uamqp-python#installation) guidance to install from source.



  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.



  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.

  [avro]: https://avro.apache.org/
  [api_reference]: https://docs.microsoft.com/python/api/overview/azure/eventhub-readme
  [schemaregistry_service]: https://aka.ms/schemaregistry
  [schemaregistry_repo]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/schemaregistry/azure-schemaregistry
  [schemaregistry_avroencoder_repo]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/schemaregistry/azure-schemaregistry-avroencoder

  ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python/sdk/eventhub/azure-eventhub/README.png)







  - Implemented backpressure for  async consumer  to address a memory leak issue. ([#36398](https://github.com/Azure/azure-sdk-for-python/issues/36398))





  - Fixed a bug where the correct URI was not being used for consumer authentication, causing issues when assigning roles at the consumer group level. ([#35337](https://github.com/Azure/azure-sdk-for-python/issues/35337))





  - Added support for non-tls connections (#34272)





  - Fixed a bug where using `EventHubProducerClient` in buffered mode could potentially drop a buffered message without actually sending it. ([#34712](https://github.com/Azure/azure-sdk-for-python/pull/34712))



  - Updated network trace logging to replace `None` values in AMQP connection info with empty strings as per the OpenTelemetry specification.



  This version and all future versions will require Python 3.8+. Python 3.7 is no longer supported.



  - Added `keep_alive` functionality on EventHubProducerClient to allow for long-living producers. [#33726](https://github.com/Azure/azure-sdk-for-python/issues/33726)



  - Added support for Python 3.12.





  - Fixed a pyAMQP error where events split across multiple TransferFrames were depleting the link credit by more than 1 credit per message. ([#32767](https://github.com/Azure/azure-sdk-for-python/pull/32767))





  - A new float keyword argument `socket_timeout` has been added to the sync and async `EventHubConsumerClient` and `EventHubProducerClient`.



  - Fixed bug [#31258](https://github.com/Azure/azure-sdk-for-python/issues/31258) where async `BlobCheckpointStore` was reprocessing old events after an error.





  - Fixed the error `end frame received on invalid channel` which was raised when a disconnect was sent by the service ([#30860](https://github.com/Azure/azure-sdk-for-python/pull/30860))
  - Fixed the error `link already closed` which was raised when the client was closing and disconnecting from the service ([#30836](https://github.com/Azure/azure-sdk-for-python/pull/30836))



   - Updated tracing ([#29934](https://github.com/Azure/azure-sdk-for-python/pull/29934)):
     - Span names renamed:
       - `Azure.EventHubs.send` to `EventHubs.send`
       - `Azure.EventHubs.message` to `EventHubs.message`
       - `Azure.EventHubs.process` to `EventHubs.process`
     - An `EventHubs.receive` span will be created upon receiving events.
     - Additional attributes added to spans:
       - `messaging.system` - messaging system (i.e., `eventhubs`)
       - `messaging.operation` - type of operation (i.e., `publish`, `receive`, or `process`)
       - `messaging.batch.message_count` - number of messages sent, received, or processed (if more than one)
     - The `component` attribute was removed from all spans.
     - All `send` spans now contain links to `message` spans. Now, `message` spans will no longer contain a link to the `send` span.
     - Message application properties will now contain values for `traceparent` (and `tracestate` if applicable)
     - Process spans will now be a direct children of message span contexts in when event handling on a per-message basis. ([#30537](https://github.com/Azure/azure-sdk-for-python/pull/30537))





  - Fixed a bug that would prevent reconnect after a long idle period, network drop (issue #28996)





  - Fixed a bug where, when `websocket-client` was not installed, the error was not caught/raised properly (issue #28453).



  Version 5.11.0 is our first stable release of the Azure Event Hubs client library based on a pure Python implemented AMQP stack.



  - A new boolean keyword argument `uamqp_transport` has been added to sync and async `EventHubProducerClient`/`EventHubConsumerClient` constructors which indicates whether to use the `uamqp` library or the default pure Python AMQP library as the underlying transport.



  - Fixed a bug that caused an error when sending batches with tracing enabled (issue #27986).
  - Fixed a bug where `EventHubSharedKeyCredential` returned an `AccessToken.token` of type `bytes` and not `str`, now matching the documentation.



  - The `message` attribute on `EventData`/`EventDataBatch`, which previously exposed the `uamqp.Message`, has been deprecated.
    - `LegacyMessage`/`LegacyBatchMessage` objects returned by the `message` attribute on `EventData`/`EventDataBatch` have been introduced to help facilitate the transition.
  - Removed uAMQP from required dependencies.
  - Adding `uamqp >= 1.6.3` as an optional dependency for use with the `uamqp_transport` keyword.
    - Added support for Python 3.11.





  - Updated the optional dependency for async transport using AMQP over WebSocket from `websocket-client` to `aiohttp` (Issue #24315, thanks @hansmbakker for the suggestion).



  This version and all future versions will require Python 3.7+. Python 3.6 is no longer supported.



  - Added the `uamqp_transport` optional parameter to the clients, to allow switching to the `uamqp` library as the transport.



  This version and all future versions will require Python 3.7+, Python 3.6 is no longer supported.



  - Fixed a bug in async `BufferedProducer` that would block when flushing the queue causing the client to freeze up (issue #23510).
  - Fixed a bug in the async `EventHubProducerClient` and `EventHubConsumerClient` that set the default value of the `transport_type` parameter in the `from_connection_string` methods to `None` rather than `TransportType.Amqp`.



  - Internal refactoring to support upcoming Pure Python AMQP-based release.
  - Updated uAMQP dependency to 1.6.0.





  - Fixed bug that prevented token refresh at regular intervals.
  - Fixed bug that was improperly passing the debug keyword argument, so that network trace debug logs are output when requested.



  - Added logging added in to track proper token refreshes & fetches, output exception reason for producer init failure.





  - Includes the following features related to buffered sending of events:
    - A new method `send_event` to `EventHubProducerClient` which allows sending single `EventData` or `AmqpAnnotatedMessage`.
    - Buffered mode sending to `EventHubProducerClient` which is intended to allow for efficient publishing of events
     without having to explicitly manage batches in the application.
      - The constructor of `EventHubProducerClient` and `from_connection_string` method takes the following new keyword arguments
       for configuration:
        - `buffered_mode`: The flag to enable/disable buffered mode sending.
        - `on_success`: The callback to be called once events have been successfully published.
        - `on_error`: The callback to be called once events have failed to be published.
        - `max_buffer_length`: The total number of events per partition that can be buffered before a flush will be triggered.
        - `max_wait_time`: The amount of time to wait for a batch to be built with events in the buffer before publishing.
      - A new method `EventHubProducerClient.flush` which flushes events in the buffer to be sent immediately.
      - A new method `EventHubProducerClient.get_buffered_event_count` which returns the number of events that are buffered and waiting to be published for a given partition.
      - A new property `EventHubProducerClient.total_buffered_event_count` which returns the total number of events that are currently buffered and waiting to be published, across all partitions.
      - A new boolean keyword argument `flush` to `EventHubProducerClient.close` which indicates whether to flush the buffer or not while closing.





  - Added support for connection using websocket and http proxy.
  - Added support for custom endpoint connection over websocket.





  - The classmethod `from_message_content` has been added to `EventData` for interoperability with the Schema Registry Avro Encoder library, and takes `content` and `content_type` as positional parameters.



  - Features related to buffered sending of events are still in beta and will not be included in this release.





  - Introduced new method `send_event` to `EventHubProducerClient` which allows sending single `EventData` or `AmqpAnnotatedMessage`.
  - Introduced buffered mode sending to `EventHubProducerClient` which is intended to allow for efficient publishing of events
   without having to explicitly manage batches in the application.
    - The constructor of `EventHubProducerClient` and `from_connection_string` method now takes the following new keyword arguments
     for configuration:
      - `buffered_mode`: The flag to enable/disable buffered mode sending.
      - `on_success`: The callback to be called once events have been successfully published.
      - `on_error`: The callback to be called once events have failed to be published.
      - `max_buffer_length`: The total number of events per partition that can be buffered before a flush will be triggered.
      - `max_wait_time`: The amount of time to wait for a batch to be built with events in the buffer before publishing.
    - Introduced new method `EventHubProducerClient.flush` which flushes events in the buffer to be sent immediately.
    - Introduced new method `EventHubProducerClient.get_buffered_event_count` which returns the number of events that are buffered and waiting to be published for a given partition.
    - Introduced new property `EventHubProducerClient.total_buffered_event_count` which returns the total number of events that are currently buffered and waiting to be published, across all partitions.
    - Introduced new boolean keyword argument `flush` to `EventHubProducerClient.close` which indicates whether to flush the buffer or not while closing.



  - Updated `EventData` internals for interoperability with the Schema Registry Avro Encoder library.





  - `from_message_data` on `EventData` has been renamed `from_message_content` for interoperability with the Schema Registry Avro Encoder library. The `data` parameter has been renamed to `content`.





  - Improved the performance of async sending and receiving.



  - The following features have been temporarily pulled out of async `EventHubProducerClient` and `EventHubConsumerClient` which will be added back in future previews as we work towards a stable release:
    - Passing the following keyword arguments to the constructors and `from_connection_string` methods of the `EventHubProducerClient` and `EventHubConsumerClient` is not supported:  `transport_type`, `http_proxy`, `custom_endpoint_address`, and `connection_verify`.





  - Added support for async `EventHubProducerClient` and `EventHubConsumerClient`.



  Version 5.8.0a1 is our first efforts to build an Azure Event Hubs client library based on pure python implemented AMQP stack.



  - The following features have been temporarily pulled out which will be added back in future previews as we work towards a stable release:
    - Async is not supported.
    - Passing the following keyword arguments to the constructors and `from_connection_string` methods of the `EventHubProducerClient` and `EventHubConsumerClient` is not supported:  `transport_type`, `http_proxy`, `custom_endpoint_address`, and `connection_verify`.



  - uAMQP dependency is removed.



  This version and all future versions will require Python 3.6+. Python 2.7 is no longer supported.



  - Added support for fixed (linear) retry backoff:
    - Sync/async `EventHubProducerClient` and `EventHubConsumerClient` constructors and `from_connection_string` take `retry_mode` as a keyword argument.



  - Fixed a bug that `EventHubProducerClient` could be reopened for sending events instead of encountering with `KeyError` when the client is previously closed (issue #21849).



  - Improved token refresh timing to prevent potentially blocking main flow when the token is about to get expired soon.
  - Updated uAMQP dependency to 1.5.1.





  - Fixed a bug for checking that `azure.eventhub.amqp.AmqpMessageHeader` and `azure.eventhub.amqp.AmqpMessageProperties` contain specific properties using the `in` keyword.



  - Updated uAMQP dependency to 1.4.3.
    - Added support for Python 3.10.
    - Fixed memory leak in win32 socketio and tlsio (issue #19777).
    - Fixed memory leak in the process of converting AMQPValue into string (issue #19777).





  - Added support for sending AMQP annotated message which allows full access to the AMQP message fields.
    - Introduced new namespace `azure.eventhub.amqp`.
    - Added new enum class `azure.eventhub.amqp.AmqpMessageBodyType` to represent the body type of the message which includes:
      - `DATA`: The body of message consists of one or more data sections and each section contains opaque binary data.
      - `SEQUENCE`: The body of message consists of one or more sequence sections and each section contains an arbitrary number of structured data elements.
      - `VALUE`: The body of message consists of one amqp-value section and the section contains a single AMQP value.
    - Introduced new class `azure.eventhub.amqp.AmqpAnnotatedMessage` for accessing low-level amqp message sections which can be instantiated for sending.
    - Introduced new classes `azure.eventhub.amqp.AmqpMessageHeader` and `azure.eventhub.amqp.AmqpMessageProperties` for accessing amqp header and properties.
    - Added new property `body_type` on `azure.eventhub.EventData` which returns `azure.eventhub.amqp.AmqpMessageBodyType`.
    - Added new read-only property `raw_amqp_message` on `azure.eventhub.EventData` which returns `azure.eventhub.amqp.AmqpAnnotatedMessage`.



  - Updated uAMQP dependency to 1.4.1.
    - Fixed a bug that attributes creation_time, absolute_expiry_time and group_sequence on MessageProperties should be compatible with integer types on Python 2.7.



  **New Features**

  - Added support for using `azure.core.credentials.AzureNamedKeyCredential` as credential for authenticating producer and consumer clients.

  **Bug Fixes**

  - Fixed bug that custom user agent string should be put in front of the built-in user agent string instead of being appended.
  - Updated uAMQP dependency to 1.4.0.
    - Fixed memory leaks in the process of link attach where source and target cython objects are not properly deallocated (#15747).
    - Improved management operation callback not to parse description value of non AMQP_TYPE_STRING type as string (#18361).

  **Notes**

  - Updated azure-core dependency to 1.14.0.



  This version follows from version 5.3.1, rather than 5.4.0b1 so that the preview idempotent producer feature is not included.

  **New Features**

  - Added support for using `azure.core.credentials.AzureSasCredential` as credential for authenticating producer and consumer clients.
  - Updated `list_ownership`, `claim_ownership`, `update_checkpoint`, `list_checkpoints` on sync and async `CheckpointStore` to support taking `**kwargs`.
    - WARNING: Implementing a custom checkpointstore that does not support taking `**kwargs` in the methods listed previously will result in the following pylint error: `W0221: Parameters differ from overridden ________ method (arguments-differ)`.
  - Updated `update_checkpoint` on sync and async `PartitionContext` to support taking `**kwargs`.

  **Bug Fixes**

  - Updated uAMQP dependency to 1.3.0.
    - Fixed bug that sending message of large size triggering segmentation fault when the underlying socket connection is lost (#13739, #14543).
    - Fixed bug in link flow control where link credit and delivery count should be calculated based on per message instead of per transfer frame (#16934).

  **Notes**

  - Updated azure-core dependency to 1.13.0.



  This version and all future versions will require Python 2.7 or Python 3.6+, Python 3.5 is no longer supported.

  **New Features**

  - Added support for idempotent publishing which is supported by the service to endeavor to reduce the number of duplicate
    events that are published.
    - `EventHubProducerClient` constructor accepts two new parameters for idempotent publishing:
      - `enable_idempotent_partitions`: A boolean value to tell the `EventHubProducerClient` whether to enable idempotency.
      - `partition_config`: The set of configurations that can be specified to influence publishing behavior
       specific to the configured Event Hub partition.
    - Introduced a new method `get_partition_publishing_properties` on `EventHubProducerClient` to inspect the information
      about the state of publishing for a partition.
    - Introduced a new property `published_sequence_number` on `EventData` to get the publishing sequence number assigned
      to the event at the time it was successfully published.
    - Introduced a new property `starting_published_sequence_number` on `EventDataBatch` to get the publishing sequence
      number assigned to the first event in the batch at the time the batch was successfully published.
    - Introduced a new class `azure.eventhub.PartitionPublishingConfiguration` which is a set of configurations that can be
      specified to influence the behavior when publishing directly to an Event Hub partition.

  **Notes**

  - Updated uAMQP dependency to 1.2.15.



  This version will be the last version to officially support Python 3.5, future versions will require Python 2.7 or Python 3.6+.

  **Bug fixes**

  - Sending empty `event_data_batch` will be a no-op now instead of raising error.



  **New Features**

  - Added a `parse_connection_string` method which parses a connection string into a properties bag, `EventHubConnectionStringProperties`, containing its component parts.
  - The constructor and `from_connection_string` method of `EventHubConsumerClient` and `EventHubProducerClient` now accept two new optional arguments:
    - `custom_endpoint_address` which allows for specifying a custom endpoint to use when communicating with the Event Hubs service,
  and is useful when your network does not allow communicating to the standard Event Hubs endpoint.
    - `connection_verify` which allows for specifying the path to the custom CA_BUNDLE file of the SSL certificate which is used to authenticate
  the identity of the connection endpoint.

  **Notes**

  - Updated uAMQP dependency to 1.2.14.



  **Bug fixes**

  - Updated `azure.eventhub.extension.__init__.py` to be compatible with pkgutil-style namespace (PR #13210, thanks @pjachowi).
  - Updated uAMQP dependency to 1.2.13
    - Added support for Python 3.9.
    - Fixed bug that macOS was unable to detect network error (#15473).
    - Fixed bug that `uamqp.ReceiveClient` and `uamqp.ReceiveClientAsync` receive messages during connection establishment (#15555).
    - Fixed bug where connection establishment on macOS with Clang 12 triggering unrecognized selector exception (#15567).
    - Fixed bug in accessing message properties triggering segmentation fault when the underlying C bytes are NULL (#15568).



  **New Features**

  - Connection strings used with `from_connection_string` methods now supports using the `SharedAccessSignature` key in leiu of `sharedaccesskey` and `sharedaccesskeyname`, taking the string of the properly constructed token as value.



  **New Features**

  - `EventHubConsumerClient` constructor accepts two new parameters for the load balancer.
      - `load_balancing_strategy`, which can be "greedy" or "balanced".
       With greedy strategy, one execution of load balancing will claim as many partitions as required to balance the load
       whereas with balanced strategy one execution of load balancing will claim at most 1 partition.
      - `partition_ownership_expiration_interval`, which allows you to customize the partition ownership expiration for load balancing.
       A consumer client may lose its owned partitions more often with a smaller expiration interval. But a larger interval
       may result in idle partitions not being claimed for longer time.
  - Added enum class `azure.eventhub.LoadBalancingStrategy` for `load_balancing_strategy`.



  **New Features**

  - `EventHubProducerClient.send_batch` accepts either an `EventDataBatch` or a finite list of `EventData`. #9181
  - Added enqueueTime to span links of distributed tracing. #9599

  **Bug fixes**

  - Fixed a bug that turned `azure.eventhub.EventhubConsumerClient` into an exclusive receiver when it has no checkpoint store. #11181
  - Updated uAMQP dependency to 1.2.7.
    - Fixed bug in setting certificate of tlsio on MacOS. #7201
    - Fixed bug that caused segmentation fault in network tracing on MacOS when setting `logging_enable` to `True` in `EventHubConsumerClient` and `EventHubProducerClient`.



  **New Features**

  - Added `EventHubConsumerClient.receive_batch()` to receive and process events in batches instead of one by one. #9184
  - `EventHubConsumerCliuent.receive()` has a new param `max_wait_time`.
  `on_event` is called every `max_wait_time` when no events are received and `max_wait_time` is not `None` or 0.
  - Param event of `PartitionContext.update_checkpoint` is now optional. The last received event is used when param event is not passed in.
  - `EventData.system_properties` has added missing properties when consuming messages from IotHub. #10408



  **Bug fixes**

  - Fixed a bug that swallowed errors when receiving events with `azure.eventhub.EventHubConsumerClient`  #9660
  - Fixed a bug that caused `get_eventhub_properties`, `get_partition_ids`, and `get_partition_properties` to raise
  an error on Azure Stack #9920



  **Breaking changes**

  - `EventData`
      - Removed deprecated property `application_properties` and deprecated method `encode_message()`.
  - `EventHubConsumerClient`
      - `on_error` would be called when `EventHubConsumerClient` failed to claim ownership of partitions.
      - `on_partition_close` and `on_partition_initialize` would be called in the case of exceptions raised by `on_event` callback.
          -  `EventHubConsumerClient` would close and re-open the internal partition receiver in this case.
      - Default starting position from where `EventHubConsumerClient` should resume receiving after recovering from an error has been re-prioritized.
          - If there is checkpoint, it will resume from the checkpoint.
          - If there is no checkpoint but `starting_position` is provided, it will resume from `starting_posititon`.
          - If there is no checkpoint or `starting_position`, it will resume from the latest position.
  - `PartitionContext`
      - `update_checkpoint` would do in-memory checkpoint instead of doing nothing when checkpoint store is not explicitly provided.
          - The in-memory checkpoints would be used for `EventHubConsumerClient` receiving recovering.
  - `get_partition_ids`, `get_partition_properties`, `get_eventhub_properties` would raise error in the case of service returning an error status code.
      - `AuthenticationError` would be raised when service returning error code 401.
      - `ConnectError` would be raised when service returning error code 404.
      - `EventHubError` would be raised when service returning other error codes.



  **Breaking changes**

  - All exceptions should now be imported from `azure.eventhub.exceptions`.
  - Introduced separate `EventHubSharedKeyCredential` objects for synchronous and asynchronous operations.
    For async, import the credentials object from the `azure.eventhub.aio` namespace.
  - `EventData`
      - Renamed property `application_properties` to `properties`.
      - `EventData` no longer has attribute `last_enqueued_event_properties` - use this on `PartitionContext` instead.
  - `EvenDataBatch`
      - `EventDataBatch.try_add` has been renamed to `EventDataBatch.add`.
      - Renamed property `size` to `size_in_bytes`.
      - Renamed attribute `max_size` to `max_size_in_bytes`.
  - `EventHubConsumerClient` and `EventHubProducerClient`
      - Renamed method `get_properties` to `get_eventhub_properties`.
      - Renamed parameters in constructor: `host` to `fully_qualified_namespace`, `event_hub_path` to `eventhub_name`.
      - Renamed parameters in `get_partition_properties`: `partition` to `partition_id`.
      - Renamed parameter `consumer_group_name` to `consumer_group` and moved that parameter from `receive` method to the constructor of `EventHubConsumerClient`.
      - Renamed parameter `initial_event_position` to `starting_position` on the `receive` method of `EventHubConsumerClient`.
      - Renamed parameter `event_hub_path` to `eventhub_name` in constructor and `from_connection_string` method of the client object.
      - `EventHubProducerClient.send` has been renamed to `send_batch` which will only accept `EventDataBatch` object as input.
      - `EventHubProducerClient.create_batch` now also takes the `partition_id` and `partition_key` as optional parameters (which are no longer specified at send).
  - Renamed module `PartitionManager` to `CheckpointStore`.
  - Receive event callback parameter has been renamed to `on_event` and now operates on a single event rather than a list of events.
  - Removed class `EventPostition`.
      - The `starting_position` parameter of the `receive` method accepts offset(`str`), sequence number(`int`), datetime (`datetime.datetime`) or `dict` of these types.
      - The `starting_position_inclusive` parameter of the `receive` method accepts `bool` or `dict` indicating whether the given event position is inclusive or not.
  - `PartitionContext` no longer has attribute `owner_id`.
  - `PartitionContext` now has attribute `last_enqueued_event_properties` which is populated if `track_last_enqueued_event_properties` is set to `True` in the `receive` method.

  **New features**

  - Added new parameter `idle_timeout` in construct and `from_connection_string` to `EventHubConsumerClient` and `EventHubProducerClient`
  after which the underlying connection will close if there is no further activity.



  **Breaking changes**

  - `EventHubClient`, `EventHubConsumer` and `EventHubProducer` has been removed. Use `EventHubProducerClient` and `EventHubConsumerClient` instead.
      - Construction of both objects is the same as it was for the previous client.
  - Introduced `EventHubProducerClient` as substitution for`EventHubProducer`.
      - `EventHubProducerClient` supports sending events to different partitions.
  - Introduced `EventHubConsumerClient` as substitution for `EventHubConsumer`.
      - `EventHubConsumerClient` supports receiving events from single/all partitions.
      - There are no longer methods which directly return `EventData`, all receiving is done via callback method: `on_events`.
  - `EventHubConsumerClient` has taken on the responsibility of `EventProcessor`.
      - `EventHubConsumerClient` now accepts `PartitionManager` to do load-balancing and checkpoint.
  - Replaced `PartitionProcessor`by four independent callback methods accepted by the `receive` method on `EventHubConsumerClient`.
      - `on_events(partition_context, events)` called when events are received.
      - `on_error(partition_context, exception` called when errors occur.
      - `on_partition_initialize(partition_context)` called when a partition consumer is opened.
      - `on_partition_close(partition_context, reason)` called when a partition consumer is closed.
  - Some modules and classes that were importable from several different places have been removed:
      - `azure.eventhub.common` has been removed. Import from `azure.eventhub` instead.
      - `azure.eventhub.client_abstract` has been removed. Use `azure.eventhub.EventHubProducerClient` or `azure.eventhub.EventHubConsumerClient` instead.
      - `azure.eventhub.client` has been removed. Use `azure.eventhub.EventHubProducerClient` or `azure.eventhub.EventHubConsumerClient` instead.
      - `azure.eventhub.producer` has been removed. Use `azure.eventhub.EventHubProducerClient` instead.
      - `azure.eventhub.consumer` has been removed. Use `azure.eventhub.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.client_async` has been removed. Use `azure.eventhub.aio.EventHubProducerClient` or `azure.eventhub.aio.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.producer_async` has been removed. Use `azure.eventhub.aio.EventHubProducerClient` instead.
      - `azure.eventhub.aio.consumer_async` has been removed. Use `azure.eventhub.aio.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.event_processor.event_processor` has been removed. Use `azure.eventhub.aio.EventHubConsumerClient` instead.
      - `azure.eventhub.aio.event_processor.partition_processor` has been removed. Use callback methods instead.
      - `azure.eventhub.aio.event_processor.partition_manager` has been removed. Import from `azure.eventhub.aio` instead.
      - `azure.eventhub.aio.event_processor.partition_context` has been removed. Import from `azure.eventhub.aio` instead.
      - `azure.eventhub.aio.event_processor.sample_partition_manager` has been removed.

  **Bug fixes**

  - Fixed bug in user-agent string not being parsed.



  **New features**

  - Added support for tracing (issue #7153).
  - Added the capability of tracking last enqueued event properties of the partition to `EventHubConsumer` .
      - Added new boolean type parameter`track_last_enqueued_event_properties` in method `EventHubClient.create_consumer()`.
      - Added new property `last_enqueued_event_properties` of `EventHubConsumer` which contains sequence_number, offset, enqueued_time and retrieval_time information.
      - By default the capability is disabled as it will cost extra bandwidth for transferring more information if turned on.

  **Breaking changes**

  - Removed support for IoT Hub direct connection.
      - [EventHubs compatible connection string](https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messages-read-builtin) of an IotHub can be used to create `EventHubClient` and read properties or events from an IoT Hub.
  - Removed support for sending EventData to IoT Hub.
  - Removed parameter `exception` in method `close()` of `EventHubConsumer` and `EventHubProcuer`.
  - Updated uAMQP dependency to 1.2.3.



  **New features**

  - Added support for automatic load balancing among multiple `EventProcessor`.
  - Added `BlobPartitionManager` which implements `PartitionManager`.
      - Azure Blob Storage is applied for storing data used by `EventProcessor`.
      - Packaged separately as a plug-in to `EventProcessor`.
      - For details, please refer to [Azure Blob Storage Partition Manager](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventhub/azure-eventhub-checkpointstoreblob-aio).
  - Added property `system_properties` on `EventData`.

  **Breaking changes**

  - Removed constructor method of `PartitionProcessor`. For initialization please implement the method `initialize`.
  - Replaced `CheckpointManager` by `PartitionContext`.
      - `PartitionContext` has partition context information and method `update_checkpoint`.
  - Updated all methods of `PartitionProcessor` to include `PartitionContext` as part of the arguments.
  - Updated accessibility of class members in `EventHub/EventHubConsumer/EventHubProducer`to be private.
  - Moved `azure.eventhub.eventprocessor` under `aio` package, which now becomes `azure.eventhub.aio.eventprocessor`.



  **New features**

  - Added method `create_batch` on the `EventHubProducer` to create an `EventDataBatch` that can then be used to add events until the maximum size is reached.
      - This batch object can then be used in the `send()` method to send all the added events to Event Hubs.
      - This allows publishers to build batches without the possibility of encountering the error around the message size exceeding the supported limit when sending events.
      - It also allows publishers with bandwidth concerns to control the size of each batch published.
  - Added new configuration parameters for exponential delay between retry operations.
      - `retry_total`: The total number of attempts to redo the failed operation.
      - `backoff_factor`: The delay time factor.
      - `backoff_max`: The maximum delay time in total.
  - Added support for context manager on `EventHubClient`.
  - Added new error type `OperationTimeoutError` for send operation.
  - Introduced a new class `EventProcessor` which replaces the older concept of [Event Processor Host](https://docs.microsoft.com/azure/event-hubs/event-hubs-event-processor-host). This early preview is intended to allow users to test the new design using a single instance of `EventProcessor`. The ability to checkpoints to a durable store will be added in future updates.
      - `EventProcessor`: EventProcessor creates and runs consumers for all partitions of the eventhub.
      - `PartitionManager`: PartitionManager defines the interface for getting/claiming ownerships of partitions and updating checkpoints.
      - `PartitionProcessor`: PartitionProcessor defines the interface for processing events.
      - `CheckpointManager`: CheckpointManager takes responsibility for updating checkpoints during events processing.

  **Breaking changes**

  - `EventProcessorHost` was replaced by `EventProcessor`, please read the new features for details.
  - Replaced `max_retries` configuration parameter of the EventHubClient with `retry_total`.




  Version 5.0.0b1 is a preview of our efforts to create a client library that is user friendly and idiomatic to the Python ecosystem. The reasons for most of the changes in this update can be found in the [Azure SDK Design Guidelines for Python](https://azuresdkspecs.z5.web.core.windows.net/PythonSpec.html). For more information, please visit https://aka.ms/azure-sdk-preview1-python.

  **New features**

  - Added new configuration parameters for creating EventHubClient.
    - `credential`: The credential object used for authentication which implements `TokenCredential` interface of getting tokens.
    - `transport_type`: The type of transport protocol that will be used for communicating with the Event Hubs service.
    - `max_retries`: The max number of attempts to redo the failed operation when an error happened.
    - for detailed information about the configuration parameters, please read the reference documentation.
  - Added new methods `get_partition_properties` and `get_partition_ids` to EventHubClient.
  - Added support for http proxy.
  - Added support for authentication using azure-identity credential.
  - Added support for transport using AMQP over WebSocket.

  **Breaking changes**

  - New error hierarchy
    - `azure.error.EventHubError`
    - `azure.error.ConnectionLostError`
    - `azure.error.ConnectError`
    - `azure.error.AuthenticationError`
    - `azure.error.EventDataError`
    - `azure.error.EventDataSendError`
  - Renamed Sender/Receiver to EventHubProducer/EventHubConsumer.
    - Renamed `add_sender` to `create_producer` and `add_receiver` to `create_consumer` in EventHubClient.
    - EventHubConsumer is now iterable.
  - Rename class azure.eventhub.Offset to azure.eventhub.EventPosition.
  - Rename method `get_eventhub_info` to `get_properties` of EventHubClient.
  - Reorganized connection management, EventHubClient is no longer responsible for opening/closing EventHubProducer/EventHubConsumer.
    - Each EventHubProducer/EventHubConsumer is responsible for its own connection management.
    - Added support for context manager on EventHubProducer and EventHubConsumer.
  - Reorganized async APIs into "azure.eventhub.aio" namespace and rename to drop the "_async" suffix.
  - Updated uAMQP dependency to 1.2.



  **BugFixes**

  - Fixed bug where datetime offset filter was using a local timestamp rather than UTC.
  - Fixed stackoverflow error in continuous connection reconnect attempts.




  **BugFixes**

  - Added support for auto reconnect on token expiration and other auth errors (issue #89).

  **Features**

  - Added ability to create ServiceBusClient from an existing SAS auth token, including
    providing a function to auto-renew that token on expiry.
  - Added support for storing a custom EPH context value in checkpoint (PR #84, thanks @konstantinmiller)




  - Support for Python 2.7 in azure.eventhub module (azure.eventprocessorhost will not support Python 2.7).
  - Parse EventData.enqueued_time as a UTC timestamp (issue #72, thanks @vjrantal)




  - Fixed bug in Azure namespace package.




  - Changes to `AzureStorageCheckpointLeaseManager` parameters to support other connection options (issue #61):
    - The `storage_account_name`, `storage_account_key` and `lease_container_name` arguments are now optional keyword arguments.
    - Added a `sas_token` argument that must be specified with `storage_account_name` in place of `storage_account_key`.
    - Added an `endpoint_suffix` argument to support storage endpoints in National Clouds.
    - Added a `connection_string` argument that, if specified, overrides all other endpoint arguments.
    - The `lease_container_name` argument now defaults to `"eph-leases"` if not specified.

  - Fix for clients failing to start if run called multipled times (issue #64).
  - Added convenience methods `body_as_str` and `body_as_json` to EventData object for easier processing of message data.




  - API stable.
  - Renamed internal `_async` module to `async_ops` for docs generation.
  - Added optional `auth_timeout` parameter to `EventHubClient` and `EventHubClientAsync` to configure how long to allow for token
    negotiation to complete. Default is 60 seconds.
  - Added optional `send_timeout` parameter to `EventHubClient.add_sender` and `EventHubClientAsync.add_async_sender` to determine the
    timeout for Events to be successfully sent. Default value is 60 seconds.
  - Reformatted logging for performance.




  - Stability improvements for EPH.
  - Updated uAMQP version.
  - Added new configuration options for Sender and Receiver; `keep_alive` and `auto_reconnect`.
    These flags have been added to the following:

    - `EventHubClient.add_receiver`
    - `EventHubClient.add_sender`
    - `EventHubClientAsync.add_async_receiver`
    - `EventHubClientAsync.add_async_sender`
    - `EPHOptions.keey_alive_interval`
    - `EPHOptions.auto_reconnect_on_error`




  - **Breaking change** `EventData.offset` will now return an object of type `~uamqp.common.Offset` rather than str.
    The original string value can be retrieved from `~uamqp.common.Offset.value`.
  - Each sender/receiver will now run in its own independent connection.
  - Updated uAMQP dependency to 0.2.0
  - Fixed issue with IoTHub clients not being able to retrieve partition information.
  - Added support for HTTP proxy settings to both EventHubClient and EPH.
  - Added error handling policy to automatically reconnect on retryable error.
  - Added keep-alive thread for maintaining an unused connection.




  - **Breaking change** Restructured library to support Python 3.7. Submodule `async` has been renamed and all classes from
    this module can now be imported from azure.eventhub directly.
  - **Breaking change** Removed optional `callback` argument from `Receiver.receive` and `AsyncReceiver.receive`.
  - **Breaking change** `EventData.properties` has been renamed to `EventData.application_properties`.
    This removes the potential for messages to be processed via callback for not yet returned
    in the batch.
  - Updated uAMQP dependency to v0.1.0
  - Added support for constructing IoTHub connections.
  - Fixed memory leak in receive operations.
  - Dropped Python 2.7 wheel support.




  - Added `namespace_suffix` to EventHubConfig() to support national clouds.
  - Added `device_id` attribute to EventData to support IoT Hub use cases.
  - Added message header to workaround service bug for PartitionKey support.
  - Updated uAMQP dependency to vRC1.




  - Updated uAMQP to latest version.
  - Further testing and minor bug fixes.




  - Updated uAQMP dependency.


