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 -
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 서비스 대시보드의 서비스 신임 정보 섹션에서 이를 확보하십시오.apikeyApp Configuration 서비스의. ApiKey App Configuration 서비스 대시보드의 서비스 신임 정보 섹션에서 이를 확보하십시오.collection_id: App Configuration 서비스 인스턴스에서 생성된 컬렉션의 ID입니다.environment_id: App Configuration 서비스 인스턴스에서 생성된 환경의 ID입니다.
그리고
init()와set_context()는 초기화 메서드이며 앱콘피그_클라이언트를 사용하여 한 번만 호출해야 합니다. 초기화되면AppConfiguration.get_instance()를 사용하여 모듈 전체에서 appconfig_client를 확보할 수 있습니다. 자세한 정보는 다른 모듈에서 appconfig_client 페치 를 참조하십시오.
사설 엔드포인트 사용
IBM Cloud 사설 네트워크를 통해서만 액세스할 수 있는 사설 엔드포인트를 사용하여 App Configuration 서비스에 연결하도록 SDK를 설정하십시오.
appconfig_client.use_private_endpoint(True);
이는 SDK에서 init 함수를 호출하기 전에 수행해야 합니다.
구성을 위해 지속적 캐시를 사용하는 옵션
애플리케이션이 다시 시작될 때 App Configuration 서비스가 중단되는 드문 시나리오에서도 애플리케이션과 SDK가 계속 작동하도록 하려면 영구 캐시를 사용하여 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 서비스로 기능 플래그 및 특성을 구성할 수 있습니다. 문자열 데이터 유형은 텍스트 문자열, JSON 또는 YAML 형식이 될 수 있습니다. SDK는 테이블에 표시된 대로 각 형식을 처리합니다.
| 기능 또는 특성 값 | 데이터 유형 | 데이터 형식 | GetCurrentValue() 에서 리턴된 데이터 유형 |
예제 출력 |
|---|---|---|---|---|
true |
BOOLEAN | 적용 불가능 | bool |
true |
25 |
숫자 | 적용 불가능 | 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 Joneswomen:- 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()