자습서: Python에서 동적 구성 사용
Azure App Configuration Python 공급자에는 기본 제공 캐싱 및 새로 고침 기능이 포함되어 있습니다. 이 자습서에서는 Python 애플리케이션에서 동적 구성을 사용하도록 설정하는 방법을 보여 줍니다.
필수 조건
- 활성 구독이 있는 Azure 계정. 체험 계정 만들기
- Azure App Configuration 저장소. 저장소를 만듭니다.
- Python 3.8 이상 - Windows에서 Python을 설정하는 방법에 대한 자세한 내용은 Windows 기반의 Python 설명서를 참조하세요.
키-값 추가
Azure App Configuration 저장소에 다음 키-값을 추가합니다. Azure Portal 또는 CLI를 사용하여 저장소에 키-값을 추가하는 방법에 대한 자세한 내용은 키-값 만들기로 이동합니다.
키 | 값 | Label | 내용 유형 |
---|---|---|---|
message | Hello World! | 비워 둡니다. | 비워 둡니다. |
sentinel | 1 | 비워 둡니다. | 비워 둡니다. |
참고 항목
sentinel 키는 다른 모든 키의 변경을 완료한 후 업데이트하는 키입니다. 앱은 Sentinel 키를 모니터링합니다. 변경이 감지되면 앱이 모든 구성 값을 새로 고칩니다. 이 방식은 앱에서 구성의 일관성을 보장하고, Azure App Configuration 저장소에 대한 전체 요청 수를 줄이는 데(모든 키의 변경 내용을 모니터링하는 것에 비해) 도움이 됩니다.
콘솔 애플리케이션
app.py라는 새 Python 파일을 만들고 다음 코드를 추가합니다.
from azure.appconfiguration.provider import load, WatchKey import os import time connection_string = os.environ.get("APPCONFIGURATION_CONNECTION_STRING") # Connecting to Azure App Configuration using connection string # Setting up to refresh when the Sentinel key is changed. config = load( connection_string=connection_string, refresh_on=[WatchKey("sentinel")], refresh_interval=10, # Default value is 30 seconds, shorted for this sample ) print("Update the `message` in your Azure App Configuration store using Azure portal or CLI.") print("First, update the `message` value, and then update the `sentinel` key value.") while (True): # Refreshing the configuration setting config.refresh() # Current value of message print(config["message"]) # Waiting before the next refresh time.sleep(5)
스크립트를 실행합니다.
python app.py
출력을 확인합니다.
Update the `message` in your Azure App Configuration store using Azure portal or CLI. First, update the `message` value, and then update the `sentinel` key value. Hello World!
다음 키-값을 Azure App Configuration 저장소로 업데이트합니다.
키 값 Label 내용 유형 message Hello World를 새로 고쳤습니다. 비워 둡니다. 비워 둡니다. sentinel 2 비워 둡니다. 비워 둡니다. 값을 업데이트하면 새로 고침 간격이 지난 후 업데이트된 값이 출력됩니다.
Hello World Refreshed!
웹 애플리케이션
다음 예제에서는 새로 고칠 수 있는 구성 값을 사용 하도록 기존 웹 애플리케이션을 업데이트 하는 방법을 보여 줍니다. 콜백은 load
함수의 on_refresh_success
키워드 인수에 제공될 수 있습니다. 이 콜백은 서버에서 구성 변경이 감지될 때 호출되며 애플리케이션의 구성 값을 업데이트하는 데 사용할 수 있습니다.
app.py
에서 구성 값을 로드하도록 Azure App Configuration을 설정합니다. 그런 다음 업데이트된 구성 값을 확인하도록 엔드포인트를 업데이트합니다.
from azure.appconfiguration.provider import load, WatchKey
azure_app_config = None # declare azure_app_config as a global variable
def on_refresh_success():
app.config.update(azure_app_config)
global azure_app_config
azure_app_config = load(connection_string=os.environ.get("AZURE_APPCONFIG_CONNECTION_STRING")
refresh_on=[WatchKey("sentinel")],
on_refresh_success=on_refresh_success,
refresh_interval=10, # Default value is 30 seconds, shortened for this sample
)
@app.route("/")
def index():
global azure_app_config
# Refresh the configuration from Azure App Configuration service.
azure_app_config.refresh()
# Access a configuration setting directly from within Flask configuration
print("Request for index page received")
context = {}
context["message"] = app.config.get("message")
return render_template("index.html", **context)
새 구성 값을 사용하도록 템플릿 index.html
을 업데이트합니다.
<!doctype html>
<head>
<title>Hello Azure App Configuration - Python Flask Example</title>
</head>
<html>
<body>
<main>
<div>
<h1>{{message}}</h1>
</div>
</main>
</body>
</html>
여기에서 전체 샘플 프로젝트를 확인할 수 있습니다.
이러한 엔드포인트가 트리거될 때마다 새로 고침 검사를 수행하여 최신 구성 값이 사용되는지 확인할 수 있습니다. 새로 고침 간격이 지나지 않았거나 새로 고침이 이미 진행 중인 경우 검사가 즉시 반환될 수 있습니다.
새로 고침이 완료되면 모든 값이 한 번에 업데이트되므로 구성은 항상 개체 내에서 일관됩니다.
참고: 새로 고침 간격이 지나지 않은 경우 새로 고침이 시도되지 않으며 즉시 반환됩니다.
다음 단계
이 자습서에서는 Python 앱을 사용하도록 설정하여 Azure App Configuration에서 구성 설정을 동적으로 새로 고칩니다. Azure 관리 ID를 사용하여 Azure App Configuration에 대한 액세스를 간소화하는 방법을 알아보려면 다음 자습서로 계속 진행하세요.
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기