Python アプリケーションで対象ユーザーに機能をロールアウトする

このガイドでは、ターゲット フィルターを使用して、Python アプリケーションの対象ユーザーに機能をロールアウトします。 このターゲット フィルターの詳細については、「対象ユーザー に機能をロールアウトする」を参照してください。

[前提条件]

機能フラグを使用する Web アプリケーションを作成する

このセクションでは、 ベータ 機能フラグ を使用して、Web ページのベータ版へのアクセスを制御する Web アプリケーションを作成します。

Python Flask プロジェクトを設定する

  1. targeting-filter-tutorialという名前のフォルダーを作成し、そこに移動します。

    mkdir targeting-filter-tutorial
    cd targeting-filter-tutorial
    
  2. 仮想環境を作成してアクティブ化します。

    # For Windows
    python -m venv venv
    venv\Scripts\activate
    
    # For macOS/Linux
    python -m venv venv
    source venv/bin/activate
    
  3. 次のパッケージをインストールしてください。

    pip install azure-appconfiguration-provider
    pip install azure-identity
    pip install featuremanagement
    pip install flask
    
  4. app.py という名前 新しいファイルを作成し、次のコードを追加します。

    from flask import Flask
    
    app = Flask(__name__)
    
    if __name__ == "__main__":
        app.run(debug=True)
    

Azure App Configuration に接続する

  1. app.py を更新し、次のコードを追加します。

    from flask import Flask
    import os
    from azure.identity import DefaultAzureCredential
    from azure.appconfiguration.provider import load
    from featuremanagement import FeatureManager
    
    app = Flask(__name__)
    
    # Get the App Configuration endpoint from environment variables
    app_config_endpoint = os.environ.get("AZURE_APPCONFIG_ENDPOINT")
    
    # Declare App Configuration and feature manager variables
    azure_app_config = None
    feature_manager = None
    
    def initialize_config():
        global azure_app_config, feature_manager
        # Load feature flags from App Configuration
        azure_app_config = load(
            endpoint=app_config_endpoint,
            credential=DefaultAzureCredential(),
            feature_flag_enabled=True,
            feature_flag_refresh_enabled=True
        )
    
        # Create a feature manager with the loaded configuration
        feature_manager = FeatureManager(azure_app_config)
    
    # Flask route before the request to refresh configuration
    @app.before_request
    def refresh_config():
        if azure_app_config:
            azure_app_config.refresh()
    
    if __name__ == "__main__":
        # Initialize configuration before starting the app
        initialize_config()
    
        app.run(debug=True)
    

    Azure App Configuration に接続して機能フラグを読み込み、自動更新を有効にして、後で機能フラグにアクセスするための FeatureManager オブジェクトを作成します。 app.before_requestデコレーターにより、各要求の前に構成が更新されます。

機能フラグを使用する

main 関数の前に次のコードを app.py ファイルに追加して、Flask アプリケーションのルート ハンドラーを作成します。 アプリケーションは、 ベータ 機能フラグが有効になっているかどうかに基づいて、さまざまなコンテンツを提供します。

@app.route("/")
def home():
    is_beta_enabled = feature_manager.is_enabled("Beta")

    title = "Home Page"
    message = "Welcome."

    if is_beta_enabled:
        title = "Beta Page"
        message = "This is a beta page."
    
    return f"""
    <!DOCTYPE html>
    <html>
        <head><title>{title}</title></head>
        <body style="display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0;">
            <h1 style="text-align: center; font-size: 5rem;">{message}</h1>
        </body>
    </html>
    """

Web アプリケーションのターゲット設定を有効にする

ターゲット設定が有効になっている機能を評価する場合は、ターゲット コンテキストが必要です。 Python では、 TargetingContext オブジェクトを作成し、機能マネージャーの is_enabled メソッドに渡す必要があります。

app.py ファイルを更新して、TargetingContext クラスをインポートし、ホーム ルートで使用します。

from flask import Flask, request
from featuremanagement import FeatureManager, TargetingContext

...

@app.route("/")
def home():
    # Get targeting context from query parameters
    user_id = request.args.get("userId", "")
    groups_param = request.args.get("groups", "")
    groups = groups_param.split(",") if groups_param else []

    targeting_context = TargetingContext(user_id=user_id, groups=groups)
    is_beta_enabled = feature_manager.is_enabled("Beta", targeting_context)
    

    title = "Home Page"
    message = "Welcome."

    if is_beta_enabled:
        title = "Beta Page"
        message = "This is a beta page."

    
    return f"""
    <!DOCTYPE html>
    <html>
        <head><title>{title}</title></head>
        <body style="display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0;">
            <h1 style="text-align: center; font-size: 5rem;">{message}</h1>
        </body>
    </html>
    """

if __name__ == "__main__":
    # Initialize configuration before starting the app
    initialize_config()

    app.run(debug=True)

ターゲット フィルターの動作

  1. AZURE_APPCONFIG_ENDPOINTという名前の環境変数を、Azure portal のストアの概要にある App Configuration ストアのエンドポイントに設定します。

    Windows コマンド プロンプトを使用する場合は、次のコマンドを実行してコマンド プロンプトを再起動し、変更が反映されるようにします。

    setx AZURE_APPCONFIG_ENDPOINT "<AppConfigurationEndpoint>"
    

    PowerShell を使用する場合は、次のコマンドを実行します。

    $Env:AZURE_APPCONFIG_ENDPOINT = "<AppConfigurationEndpoint>"
    

    macOS または Linux を使用する場合は、次のコマンドを実行します。

    export AZURE_APPCONFIG_ENDPOINT='<AppConfigurationEndpoint>'
    
  2. アプリケーションを実行します。

    python app.py
    
  3. ブラウザーを開き、ターミナルに表示されているアドレス (既定では http://127.0.0.1:5000) に移動します。 アプリの既定のビューが表示されます。

    既定のあいさつメッセージを示すアプリのスクリーンショット。

  4. URL にクエリ パラメーターとして userId を追加して、ユーザー ID を指定します。 localhost:5000/?userId=test@contoso.comを訪問. ターゲット ユーザーとして test@contoso.com が指定されているため、ベータ 版ページが表示されます。

    ベータ 版ページを示すアプリのスクリーンショット。

  5. localhost:5000/?userId=testuser@contoso.comを訪問. testuser@contoso.comは除外されたユーザーとして指定されているため、ベータ 版ページを表示できません。

    既定のコンテンツを示すアプリのスクリーンショット。

次のステップ

機能フィルターの詳細については、次のドキュメントに進んでください。

Python 機能管理ライブラリの詳細については、次のドキュメントに進んでください。