Python 用 App Configuration サーバー SDK
App Configuration サービスは、Python アプリケーションと統合される SDK を提供します。
Python 用サーバー SDK の統合
App Configuration サービスは、Python アプリケーションと統合される SDK を提供します。 App Configuration SDK を統合することで、機能フラグまたはプロパティーの値を評価できます。
-
SDK をインストールするには、以下のいずれかの方法を使用します。
使用
pippip install --upgrade ibm-appconfiguration-python-sdk使用
easy_installeasy_install --upgrade ibm-appconfiguration-python-sdk -
次のコードを使用して、Python アプリケーション・コードに SDK モジュールを組み込みます。
from ibm_appconfiguration import AppConfiguration, Feature, Property, ConfigurationType -
App Configuration サービス・インスタンスと接続するように SDK を初期化します。
appconfig_client = AppConfiguration.get_instance() appconfig_client.init(region='region', guid='guid', apikey='apikey') appconfig_client.set_context(collection_id='airlines-webapp', environment_id='dev')ここで、
region: App Configuration サービスインスタンスが作成されるリージョン名。 対応拠点のリストは こちら。 例:us-south、au-sydなど。guid: App Configuration サービスの GUID。 これは、App Configuration サービス・ダッシュボードの「サービス資格情報」セクションから取得します。apikeyApp Configuration サービスの。 ApiKey これは、App Configuration サービス・ダッシュボードの「サービス資格情報」セクションから取得します。collection_id: App Configuration サービスインスタンスで作成されたコレクションのID。environment_id: App Configuration サービスインスタンスで作成された環境の ID。
その
init()とset_context()は初期化メソッドで、appconfig_clientを使って一度だけ呼び出す必要があります。 appconfig_client は、初期化されると、AppConfiguration.get_instance()を使用してモジュール間で取得できます。 詳しくは、 他のモジュールにまたがる appconfig_client の取り出し を参照してください。
プライベート・エンドポイントの使用
IBM Cloud プライベート・ネットワークを介してのみアクセス可能なプライベート・エンドポイントを使用して、 App Configuration サービスに接続するように SDK を設定します。
appconfig_client.use_private_endpoint(True);
これは、SDK で init 関数を呼び出す前に行う必要があります。
構成に永続キャッシュを使用するオプション
アプリケーションとSDKが、 App Configuration、アプリケーションが再起動する間にサービスがダウンするというありえないシナリオの間でも操作を継続できるように、永続キャッシュを使用してSDKが動作するように設定できます。 SDK は永続キャッシュを使用して、アプリケーションの再起動後に使用可能な App Configuration データを保管します。
# 1. default (without persistent cache)
appconfig_client.set_context(collection_id='airlines-webapp', environment_id='dev')
# 2. optional (with persistent cache)
appconfig_client.set_context(collection_id='airlines-webapp', environment_id='dev', options={
'persistent_cache_dir': '/var/lib/docker/volumes/'
})
ここで、
-
persistent_cache_dir:ユーザに対して読み取りと書き込みのパーミッションが与えられているディレクトリへの絶対パス。 SDKは指定されたディレクトリにファイルappconfiguration.jsonを作成し、 App Configuration サービス情報を保存する永続キャッシュとして使用する。パーシステントキャッシュが有効な場合、SDKはパーシステントキャッシュに最後の既知の良好な設定を保持します。 App Configuration サーバーに到達できない場合、永続キャッシュにある最新のコンフィギュレーションがアプリケーションにロードされ、動作を継続する。
指定されたディレクトリーに作成されたキャッシュ・ファイルが、いずれの場合も失われたり削除されたりしていないことを確認してください。 例えば、kubernetes ポッドが再始動され、キャッシュ・ファイル (appconfiguration.json) がポッドの一時ボリュームに保管された場合を考えてみます。 ポッドが再始動すると、kubernetes はポッド内の ephermal ボリュームを破棄します。その結果、キャッシュ・ファイルは削除されます。
そのため、SDK によって作成されたキャッシュ・ファイルが、永続ディレクトリーの正しい絶対パスを指定することによって、常に永続ボリュームに保管されるようにしてください。
オフライン・オプション
SDK はまた、構成を供給するとともに、App Configuration サービスに接続せずに機能フラグおよびプロパティーの評価を実行するように設計されています。
appconfig_client.set_context(collection_id='collection_id', environment_id='environment_id', options={
'bootstrap_file': 'saflights/flights.json',
'live_config_update_enabled': False
})
ここで、
bootstrap_file:設定の詳細を含むJSONファイルの絶対パス。 必ず正しい JSON ファイルを指定してください。 このファイルは、 IBM Cloud App Configuration CLI のibmcloud ac exportコマンドを使用して生成できます。live_config_update_enabled:サーバーからのライブ設定更新。 新しい構成値をサーバーから取得する必要がない場合は、この値をFalseに設定する。 この値はデフォルトでは、True に設定されています。
機能関連 API およびプロパティー関連 API の使用例
機能関連 API およびプロパティー関連 API の使用については、リスト化されている例を参照してください。
単一の機能を取得する
feature = appconfig_client.get_feature('online-check-in') # feature can be None incase of an invalid feature id
if feature is not None:
print(f'Feature Name : {0}'.format(feature.get_feature_name()))
print(f'Feature Id : {0}'.format(feature.get_feature_id()))
print(f'Feature Data Type : {0}'.format(feature.get_feature_data_type()))
if feature.is_enabled():
# feature flag is enabled
else:
# feature flag is disabled
すべての機能を取得する
features_dictionary = appconfig_client.get_features()
機能評価
feature.get_current_value(entity_id, entity_attributes) メソッドを使って、フィーチャー・フラグの値を評価することができる。 このメソッドは、評価に基づいて、「有効」、「無効」、または「オーバーライド済み」のいずれかの値を返します。 戻り値のデータ・タイプは、機能フラグのデータ・タイプと一致します。
entity_id = "john_doe"
entity_attributes = {
'city': 'Bangalore',
'country': 'India'
}
feature_value = feature.get_current_value(entity_id=entity_id, entity_attributes=entity_attributes)
-
entity_id: エンティティーの ID。 これは、フィーチャーが評価されるエンティティーに関連するストリング ID です。 例えば、エンティティーは、モバイル・デバイス上で実行されるアプリのインスタンス、クラウド上で実行されるマイクロサービス、またはそのマイクロサービスを実行するインフラストラクチャーのコンポーネントの場合があります。 いずれかのエンティティーが App Configuration と対話するには、固有のエンティティー ID を提供する必要があります。 -
entity_attributes: 指定されたエンティティーを定義する属性名とその値で構成される JSON オブジェクト。 フィーチャー・フラグがターゲット定義で構成されていない場合、これはオプション・パラメーターです。 ターゲットが構成されている場合は、ルール評価のためにentity_attributesを指定する必要があります。 属性は、セグメントを定義するために使用されるパラメーターです。 SDK は、属性値を使用して、指定されたエンティティーがターゲット・ルールを満たしているかどうかを判別し、適切なフィーチャー・フラグ値を返します。
単一のプロパティーを取得する
property = appconfig_client.get_property('check-in-charges') # property can be None incase of an invalid property id
if property is not None:
print(f'Property Name : {0}'.format(property.get_property_name()))
print(f'Property Id : {0}'.format(property.get_property_id()))
print(f'Property Data Type : {0}'.format(property.get_property_data_type()))
すべてのプロパティーを取得する
properties_dictionary = appconfig_client.get_properties()
プロパティーの評価
property.get_current_value(entity_id=entity_id, entity_attributes=entity_attributes) メソッドを使って、不動産の価値を評価することができる。 このメソッドは、評価に基づいて、デフォルトのプロパティー値またはオーバーライドされた値を返します。 戻り値のデータ・タイプは、プロパティーのデータ・タイプと一致します。
entity_id = "john_doe"
entity_attributes = {
'city': 'Bangalore',
'country': 'India'
}
property_value = property.get_current_value(entity_id=entity_id, entity_attributes=entity_attributes)
-
entity_id: エンティティーの ID。 これは、プロパティーが評価されるエンティティーに関連するストリング ID です。 例えば、エンティティーは、モバイル・デバイス上で実行されるアプリのインスタンス、クラウド上で実行されるマイクロサービス、またはそのマイクロサービスを実行するインフラストラクチャーのコンポーネントの場合があります。 いずれかのエンティティーが App Configuration と対話するには、固有のエンティティー ID を提供する必要があります。 -
entity_attributes: 指定されたエンティティーを定義する属性名とその値で構成される JSON オブジェクト。 プロパティーがターゲット定義で構成されていない場合、これはオプション・パラメーターです。 ターゲットが構成されている場合は、ルール評価のためにentity_attributesを指定する必要があります。 属性は、セグメントを定義するために使用されるパラメーターです。 SDK は、属性値を使用して、指定されたエンティティーがターゲット・ルールを満たしているかどうかを判別し、適切なプロパティー値を返します。
各種モジュール全体にわたる appconfig_client のフェッチ
SDKが初期化されると、appconfig_clientは図のように他のモジュール間で取得できる:
# **other modules**
from ibm_appconfiguration import AppConfiguration
appconfig_client = AppConfiguration.get_instance()
feature = appconfig_client.get_feature('online-check-in')
enabled = feature.is_enabled()
feature_value = feature.get_current_value(entity_id, entity_attributes)
サポート対象データ・タイプ
App Configuration を使用して、ブール、数値、文字列の各データ・タイプをサポートする機能フラグとプロパティーを構成できます。 「文字列」データ・タイプは、テキスト文字列、JSON、YAML のフォーマットにできます。 SDK は、表に示されているように各フォーマットを処理します。
| フィーチャーまたはプロパティーの値 | データ型 | データ形式 | GetCurrentValue() によって返されるデータのタイプ |
出力例 |
|---|---|---|---|---|
true |
BOOLEAN | 適用外 | bool |
true |
25 |
NUMERIC | 適用外 | int |
25 |
| "a string text" | STRING | TEXT | string |
a string text |
{"firefox": {"name": "Firefox","pref_url": "about:config"}} |
ストリング | JSON | Dictionary or List of Dictionary |
{'firefox': {'name': 'Firefox', 'pref_url': 'about:config'}} |
men:- John Smith- Bill Jones ¥ n women:- Mary Smith- Susan Williams |
STRING | YAML | Dictionary |
{'men': ['John Smith', 'Bill Jones'], 'women': ['Mary Smith', 'Susan Williams']} |
機能フラグ
feature = appconfig_client.get_feature('json-feature')
feature.get_feature_data_type() // STRING
feature.get_feature_data_format() // JSON
feature.get_current_value(entityId, entityAttributes) // returns single dictionary object or list of dictionary object
// Example Below
// input json :- [{"role": "developer", "description": "do coding"},{"role": "tester", "description": "do testing"}]
// expected output :- "do coding"
tar_val = feature.get_current_value(entityId, entityAttributes)
expected_output = tar_val[0]['description']
// input json :- {"role": "tester", "description": "do testing"}
// expected output :- "tester"
tar_val = feature.get_current_value(entityId, entityAttributes)
expected_output = tar_val['role']
feature = appconfig_client.getFeature('yaml-feature')
feature.get_feature_data_type() // STRING
feature.get_feature_data_format() // YAML
feature.get_current_value(entityId, entityAttributes) // returns dictionary object
// Example Below
// input yaml string :- "---\nrole: tester\ndescription: do_testing"
// expected output :- "do_testing"
tar_val = feature.get_current_value(entityId, entityAttributes)
expected_output = tar_val['description']
プロパティー (Property)
property = appconfig_client.get_property('json-property')
property.get_property_data_type() // STRING
property.get_property_data_format() // JSON
property.get_current_value(entityId, entityAttributes) // returns single dictionary object or list of dictionary object
// Example Below
// input json :- [{"role": "developer", "description": "do coding"},{"role": "tester", "description": "do testing"}]
// expected output :- "do coding"
tar_val = property.get_current_value(entityId, entityAttributes)
expected_output = tar_val[0]['description']
// input json :- {"role": "tester", "description": "do testing"}
// expected output :- "tester"
tar_val = property.get_current_value(entityId, entityAttributes)
expected_output = tar_val['role']
property = appconfig_client.get_property('yaml-property')
property.get_property_data_type() // STRING
property.get_property_data_format() // YAML
property.get_current_value(entityId, entityAttributes) // returns dictionary object
// Example Below
// input yaml string :- "---\nrole: tester\ndescription: do_testing"
// expected output :- "do_testing"
tar_val = property.get_current_value(entityId, entityAttributes)
expected_output = tar_val['description']
機能およびプロパティー・データの変更のリスナーを設定します。
SDKは、機能フラグやプロパティのコンフィギュレーションが変更されたときにリアルタイムで通知するメカニズムを提供します。 同じappconfig_clientを使うことで、設定変更を購読できる。
def configuration_update(self):
print('Received updates on configurations')
# **add your code**
# To find the effect of any configuration changes, you can call the feature or property related methods
# feature = appconfig_client.getFeature('online-check-in')
# new_value = feature.get_current_value(entity_id, entity_attributes)
appconfig_client.register_configuration_update_listener(configuration_update)
最新データを取り出す
appconfig_client.fetch_configurations()