App Configuration 伺服器 SDK for Python

App Configuration 服務提供 SDK,以與 Python 應用程式整合。

整合伺服器 SDK for Python

App Configuration 服務提供 SDK,以與 Python 應用程式整合。 您可以透過整合 App Configuration SDK 來評估特性旗標或內容的值。

  1. 請使用下列其中一種方法來安裝 SDK:

    使用 pip

    pip install --upgrade ibm-appconfiguration-python-sdk
    

    使用 easy_install

    easy_install --upgrade ibm-appconfiguration-python-sdk
    
  2. 在 Python 應用程式碼中,包含 SDK 模組:

    from ibm_appconfiguration import AppConfiguration, Feature, Property, ConfigurationType
    
  3. 起始設定 sdk 以使用 App Configuration 服務實例進行連接。

    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 服務儀表板的服務認證區段取得它。
    • apikey: App Configuration 服務的 ApiKey。 請從 App Configuration 服務儀表板的服務認證區段取得它。
    • collection_id: 在 App Configuration 服務實例中建立的集合 ID。
    • environment_id: 在 App Configuration 服務實例中建立之環境的 ID。

    init()set_context() 是起始設定方法,應該使用 appconfig_client 只呼叫一次。 起始設定時,可以使用 AppConfiguration.get_instance() 跨模組取得 appconfig_client。 如需相關資訊,請參閱 跨其他模組提取 appconfig_client

使用專用端點

設定 SDK,以使用只能透過 IBM Cloud 專用網路存取的專用端點來連接至 App Configuration 服務。

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 Pod 重新啟動,且快取檔 (appconfiguration.json) 儲存在 Pod 的暫時磁區中。 當 Pod 重新啟動時,kubernetes 會毀損 Pod 中的 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 的範例。

取得單一特性

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 服務來配置特性旗標和內容,支援下列資料類型: 布林、數值和字串。 「字串」資料類型可以是 TEXT 字串、JSON 或 YAML 格式。 SDK 處理每一個格式,如表格中所示。

輸出範例
特性或內容值 資料類型 資料格式 GetCurrentValue() 傳回的資料類型 輸出範例
true BOOLEAN 不適用 bool true
25 NUMERIC 不適用 int 25
「字串文字」 STRING TEXT string a string text
{"firefox": {
"name": "Firefox",
"pref_url": "about:config"
}}
STRING JSON Dictionary or List of Dictionary {'firefox': {'name': 'Firefox', 'pref_url': 'about:config'}}
men:
- John Smith
- Bill Jones
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 = 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()