Skip to main content

Microsoft App Configuration Data Library for Python

Project description

Azure App Configuration client library for Python

Azure App Configuration is a managed service that helps developers centralize their application configurations simply and securely.

Modern programs, especially programs running in a cloud, generally have many components that are distributed in nature. Spreading configuration settings across these components can lead to hard-to-troubleshoot errors during an application deployment. Use App Configuration to securely store all the settings for your application in one place.

Use the client library for App Configuration to create and manage application configuration settings.

Source code | Package (Pypi) | Package (Conda) | API reference documentation | Product documentation

Getting started

Install the package

Install the Azure App Configuration client library for Python with pip:

pip install azure-appconfiguration

Prerequisites

To create a Configuration Store, you can use the Azure Portal or Azure CLI.

After that, create the Configuration Store:

az appconfig create --name <config-store-name> --resource-group <resource-group-name> --location eastus

Authenticate the client

In order to interact with the App Configuration service, you'll need to create an instance of the AzureAppConfigurationClient class. To make this possible, you can either use the connection string of the Configuration Store or use an AAD token.

Use connection string

Get credentials

Use the Azure CLI snippet below to get the connection string from the Configuration Store.

az appconfig credential list --name <config-store-name>

Alternatively, get the connection string from the Azure Portal.

Create client

Once you have the value of the connection string, you can create the AzureAppConfigurationClient:

import os
from azure.appconfiguration import AzureAppConfigurationClient

CONNECTION_STRING = os.environ["APPCONFIGURATION_CONNECTION_STRING"]

# Create app config client
client = AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING)

Use AAD token

Here we demonstrate using DefaultAzureCredential to authenticate as a service principal. However, AzureAppConfigurationClient accepts any azure-identity credential. See the azure-identity documentation for more information about other credentials.

Create a service principal (optional)

This Azure CLI snippet shows how to create a new service principal. Before using it, replace "your-application-name" with the appropriate name for your service principal.

Create a service principal:

az ad sp create-for-rbac --name http://my-application --skip-assignment

Output:

{
    "appId": "generated app id",
    "displayName": "my-application",
    "name": "http://my-application",
    "password": "random password",
    "tenant": "tenant id"
}

Use the output to set AZURE_CLIENT_ID ("appId" above), AZURE_CLIENT_SECRET ("password" above) and AZURE_TENANT_ID ("tenant" above) environment variables. The following example shows a way to do this in Bash:

export AZURE_CLIENT_ID="generated app id"
export AZURE_CLIENT_SECRET="random password"
export AZURE_TENANT_ID="tenant id"

Assign one of the applicable App Configuration roles to the service principal.

Create a client

Once the AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID environment variables are set, DefaultAzureCredential will be able to authenticate the AzureAppConfigurationClient.

Constructing the client also requires your configuration store's URL, which you can get from the Azure CLI or the Azure Portal. In the Azure Portal, the URL can be found listed as the service "Endpoint"

from azure.identity import DefaultAzureCredential
from azure.appconfiguration import AzureAppConfigurationClient

credential = DefaultAzureCredential()

client = AzureAppConfigurationClient(base_url="your_endpoint_url", credential=credential)

Key concepts

Configuration Setting

A Configuration Setting is the fundamental resource within a Configuration Store. In its simplest form it is a key and a value. However, there are additional properties such as the modifiable content type and tags fields that allow the value to be interpreted or associated in different ways.

The Label property of a Configuration Setting provides a way to separate Configuration Settings into different dimensions. These dimensions are user defined and can take any form. Some common examples of dimensions to use for a label include regions, semantic versions, or environments. Many applications have a required set of configuration keys that have varying values as the application exists across different dimensions.

For example, MaxRequests may be 100 in "NorthAmerica", and 200 in "WestEurope". By creating a Configuration Setting named MaxRequests with a label of "NorthAmerica" and another, only with a different value, in the "WestEurope" label, an application can seamlessly retrieve Configuration Settings as it runs in these two dimensions.

Properties of a Configuration Setting:

key : str
label : str
content_type : str
value : str
last_modified : str
read_only : bool
tags : dict
etag : str

Snapshot

Azure App Configuration allows users to create a point-in-time snapshot of their configuration store, providing them with the ability to treat settings as one consistent version. This feature enables applications to hold a consistent view of configuration, ensuring that there are no version mismatches to individual settings due to reading as updates were made. Snapshots are immutable, ensuring that configuration can confidently be rolled back to a last-known-good configuration in the event of a problem.

Examples

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

Create a Configuration Setting

Create a Configuration Setting to be stored in the Configuration Store. There are two ways to store a Configuration Setting:

  • add_configuration_setting creates a setting only if the setting does not already exist in the store.
config_setting = ConfigurationSetting(
    key="MyKey", label="MyLabel", value="my value", content_type="my content type", tags={"my tag": "my tag value"}
)
added_config_setting = client.add_configuration_setting(config_setting)
  • set_configuration_setting creates a setting if it doesn't exist or overrides an existing setting.
added_config_setting.value = "new value"
added_config_setting.content_type = "new content type"
updated_config_setting = client.set_configuration_setting(added_config_setting)

Set and clear read-only for a configuration setting.

  • Set a configuration setting to be read-only.
read_only_config_setting = client.set_read_only(updated_config_setting)
  • Clear read-only for a configuration setting.
read_write_config_setting = client.set_read_only(updated_config_setting, False)

Get a Configuration Setting

Get a previously stored Configuration Setting.

fetched_config_setting = client.get_configuration_setting(key="MyKey", label="MyLabel")

Delete a Configuration Setting

Delete an existing Configuration Setting.

client.delete_configuration_setting(key="MyKey", label="MyLabel")

List Configuration Settings

List all configuration settings filtered with label_filter and/or key_filter and/or tags_filter.

config_settings = client.list_configuration_settings(key_filter="MyKey*", tags_filter=["my tag1=my tag1 value"])
for config_setting in config_settings:
    print(config_setting)

List revisions

List revision history of configuration settings filtered with label_filter and/or key_filter and/or tags_filter.

items = client.list_revisions(key_filter="MyKey", tags_filter=["my tag=my tag value"])
for item in items:
    print(item)

List labels

List labels of all configuration settings.

print("List all labels in resource")
config_settings = client.list_labels()
for config_setting in config_settings:
    print(config_setting)

print("List labels by exact match")
config_settings = client.list_labels(name="my label1")
for config_setting in config_settings:
    print(config_setting)

print("List labels by wildcard")
config_settings = client.list_labels(name="my label*")
for config_setting in config_settings:
    print(config_setting)

Create a Snapshot

from azure.appconfiguration import ConfigurationSettingsFilter

filters = [ConfigurationSettingsFilter(key="my_key1", label="my_label1")]
response = client.begin_create_snapshot(name=snapshot_name, filters=filters)
created_snapshot = response.result()

Get a Snapshot

received_snapshot = client.get_snapshot(name=snapshot_name)

Archive a Snapshot

archived_snapshot = client.archive_snapshot(name=snapshot_name)

Recover a Snapshot

recovered_snapshot = client.recover_snapshot(name=snapshot_name)

List Snapshots

for snapshot in client.list_snapshots():
    print(snapshot)

List Configuration Settings of a Snapshot

for config_setting in client.list_configuration_settings(snapshot_name=snapshot_name):
    print(config_setting)

Async APIs

Async client is supported. To use the async client library, import the AzureAppConfigurationClient from package azure.appconfiguration.aio instead of azure.appconfiguration.

import os
from azure.appconfiguration.aio import AzureAppConfigurationClient

CONNECTION_STRING = os.environ["APPCONFIGURATION_CONNECTION_STRING"]

# Create an app config client
client = AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING)

This async AzureAppConfigurationClient has the same method signatures as the sync ones except that they're async.
For instance, retrieve a Configuration Setting asynchronously:

fetched_config_setting = await client.get_configuration_setting(key="MyKey", label="MyLabel")

To list configuration settings, call list_configuration_settings operation synchronously and iterate over the returned async iterator asynchronously:

config_settings = client.list_configuration_settings(key_filter="MyKey*", tags_filter=["my tag1=my tag1 value"])
async for config_setting in config_settings:
    print(config_setting)

Troubleshooting

See the troubleshooting guide for details on how to diagnose various failure scenarios.

Next steps

More sample code

Several App Configuration client library samples are available to you in this GitHub repository. These include:

For more details see the samples README.

Contributing

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

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

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Release History

1.7.1 (2024-08-22)

Bugs Fixed

  • Fixed a bug in serializing/deserializing tags filter in ConfigurationSnapshot.

1.7.0 (2024-08-15)

Features Added

  • Added operation list_labels() for listing configuration setting labels.
  • Supported filtering by configuration setting tags in list_configuration_settings() and list_revisions().
  • Added a new property tags to ConfigurationSettingsFilter to support filtering settings with tags filter for snapshot.

Bugs Fixed

  • Fixed a bug where the feature_id of FeatureFlagConfigurationSetting will be different from id customer field, and may overwrite the original customer-defined value if different from the FeatureFlagConfigurationSetting key suffix.

Other Changes

  • Updated the default api_version to "2023-11-01".
  • Published enum LabelFields and model ConfigurationSettingLabel.
  • Published enum SnapshotFields, and accepted the type for fields parameter in get_snapshot() and list_snapshots().
  • Published enum ConfigurationSettingFields, and accepted the type for fields parameter in list_configuration_settings() and list_revisions().
  • Published enum SnapshotComposition, and accepted the type for ConfigurationSnapshot property composition_type and begion_create_snapshot() kwarg composition_type.

1.6.0 (2024-04-09)

Features Added

  • Exposed send_request() method in each client to send custom requests using the client's existing pipeline.
  • Supported to get page ETag while iterating list_configuration_setting() result by page.

Bugs Fixed

  • Fixed a bug in consuming "etag" value in sync operation set_configuration_setting().
  • Changed invalid default value None to False for property enabled in FeatureFlagConfigurationSetting.
  • Fixed the issue that description, display_name and other customer fields are missing when de/serializing FeatureFlagConfigurationSetting objects.

1.6.0b2 (2024-03-21)

Bugs Fixed

  • Changed invalid default value None to False for property enabled in FeatureFlagConfigurationSetting.
  • Fixed the issue that description, display_name and other customer fields are missing when de/serializing FeatureFlagConfigurationSetting objects.

1.6.0b1 (2024-03-14)

Features Added

  • Exposed send_request() method in each client to send custom requests using the client's existing pipeline.
  • Supported to get page ETag while iterating list_configuration_setting() result by page.

Bugs Fixed

  • Fixed a bug in consuming "etag" value in sync operation set_configuration_setting().

1.5.0 (2023-11-09)

Other Changes

  • Supported datetime type for keyword argument accept_datetime in get_snapshot_configuration_settings(), list_snapshot_configuration_settings() and list_revisions().
  • Bumped minimum dependency on azure-core to >=1.28.0.
  • Updated the default api_version to "2023-10-01".
  • Removed etag keyword documentation in set_read_only() as it's not in use.
  • Added support for Python 3.12.
  • Python 3.7 is no longer supported. Please use Python version 3.8 or later.

1.5.0b3 (2023-10-10)

Breaking Changes

  • Renamed parameter name in list_snapshot_configuration_settings() to snapshot_name.
  • Removed keyword argument accept_datetime in list_snapshot_configuration_settings().
  • Moved operation list_snapshot_configuration_settings() to an overload of list_configuration_settings(), and moved the parameter snapshot_name to keyword.
  • Published enum SnapshotStatus, and accepted the type for status parameter in list_snapshots() and status property in Snapshot model.
  • Renamed model Snapshot to ConfigurationSnapshot.
  • Renamed model ConfigurationSettingFilter to ConfigurationSettingsFilter.

1.5.0b2 (2023-08-02)

Bugs Fixed

  • Fixed a bug in deserializing and serializing Snapshot when filters property is None.
  • Fixed a bug when creating FeatureFlagConfigurationSetting from SDK but having an error in portal.(#31326)

1.5.0b1 (2023-07-11)

Features Added

  • Added support for Snapshot CRUD operations.

Bugs Fixed

  • Fixed async update_sync_token() to use async/await keywords.

Other Changes

  • Bumped minimum dependency on azure-core to >=1.25.0.
  • Updated the default api_version to "2022-11-01-preview".

1.4.0 (2022-02-13)

Other Changes

  • Python 2.7 is no longer supported. Please use Python version 3.7 or later.
  • Bumped minimum dependency on azure-core to >=1.24.0.
  • Changed the default async transport from AsyncioRequestsTransport to the one used in current azure-core (AioHttpTransport). (#26427)
  • Dropped msrest requirement.
  • Added dependency isodate with version range >=0.6.0.

1.3.0 (2021-11-10)

Bugs Fixed

  • Fixed the issue that data was persisted according to an incorrect schema/in an incorrect format (#20518)

    SecretReferenceConfigurationSetting in 1.2.0 used "secret_uri" rather than "uri" as the schema keywords which broken inter-operation of SecretReferenceConfigurationSetting between SDK and the portal.

    Please:

    • Use 1.3.0+ for any SecretReferenceConfigurationSetting uses.
    • Call a get method for existing SecretReferenceConfigurationSettings and set them back to correct the format.

1.2.0 (2021-07-06)

Features Added

  • Added FeatureFlagConfigurationSetting and SecretReferenceConfigurationSetting models
  • AzureAppConfigurationClient can now be used as a context manager.
  • Added update_sync_token() to update sync tokens from Event Grid notifications.

1.2.0b2 (2021-06-08)

Features

  • Added context manager functionality to the sync and async AzureAppConfigurationClients.

Fixes

  • Fixed a deserialization bug for FeatureFlagConfigurationSetting and SecretReferenceConfigurationSetting.

1.2.0b1 (2021-04-06)

Features

  • Added method update_sync_token() to include sync tokens from EventGrid notifications.
  • Added SecretReferenceConfigurationSetting type to represent a configuration setting that references a KeyVault Secret.
  • Added FeatureFlagConfigurationSetting type to represent a configuration setting that controls a feature flag.

1.1.1 (2020-10-05)

Features

  • Improved error message if Connection string secret has incorrect padding. (#14140)

1.1.0 (2020-09-08)

Features

  • Added match condition support for set_read_only() method. (#13276)

1.0.1 (2020-08-10)

Fixes

  • Doc & Sample fixes

1.0.0 (2020-01-06)

Features

  • Added AAD auth support. (#8924)

Breaking changes

  • list_configuration_settings() & list_revisions() now take string key/label filter instead of keys/labels list. (#9066)

1.0.0b6 (2019-12-03)

Features

  • Added sync-token support. (#8418)

Breaking changes

  • Combined set_read_only & clear_read_only to be set_read_only(True/False). (#8453)

1.0.0b5 (2019-10-30)

Breaking changes

  • etag and match_condition of delete_configuration_setting() are now keyword argument only. (#8161)

1.0.0b4 (2019-10-07)

  • Added conditional operation support
  • Added set_read_only() and clear_read_only() methods

1.0.0b3 (2019-09-09)

  • New azure app configuration

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure-appconfiguration-1.7.1.tar.gz (113.7 kB view details)

Uploaded Source

Built Distribution

azure_appconfiguration-1.7.1-py3-none-any.whl (91.0 kB view details)

Uploaded Python 3

File details

Details for the file azure-appconfiguration-1.7.1.tar.gz.

File metadata

File hashes

Hashes for azure-appconfiguration-1.7.1.tar.gz
Algorithm Hash digest
SHA256 3ebe41e9be3f4ae6ca61e5dbc42c4b7cc007a01054a8506501a26dfc199fd3ec
MD5 f9054e3e3d9361b36ec46af66489a6cd
BLAKE2b-256 2cffcd3804d1aa1789f393a3174ca2b701edf7f0092c615ab384fd065afd4433

See more details on using hashes here.

File details

Details for the file azure_appconfiguration-1.7.1-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_appconfiguration-1.7.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6e62b040a0210071be4423aafbdca3b053884c0d412855e3f8eff8e8d0b1a02b
MD5 1a1bbca417147d4c6bd5926ea7806d2a
BLAKE2b-256 fa6fe4d2645a70a2e19c23e47350737e7f6d44bc883666c9099c79fb775a4e10

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page