|
| 1 | +# ------------------------------------------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License.txt in the project root for |
| 4 | +# license information. |
| 5 | +# ------------------------------------------------------------------------- |
| 6 | + |
| 7 | +import uuid |
| 8 | +import os |
| 9 | +from quart import Quart, request, session |
| 10 | +from quart.sessions import SecureCookieSessionInterface |
| 11 | +from azure.appconfiguration.provider import load |
| 12 | +from azure.identity import DefaultAzureCredential |
| 13 | +from featuremanagement.aio import FeatureManager |
| 14 | +from featuremanagement import TargetingContext |
| 15 | + |
| 16 | +try: |
| 17 | + from azure.monitor.opentelemetry import configure_azure_monitor # pylint: disable=ungrouped-imports |
| 18 | + |
| 19 | + # Configure Azure Monitor |
| 20 | + configure_azure_monitor(connection_string=os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")) |
| 21 | +except ImportError: |
| 22 | + pass |
| 23 | + |
| 24 | +app = Quart(__name__) |
| 25 | +app.session_interface = SecureCookieSessionInterface() |
| 26 | +app.secret_key = os.urandom(24) |
| 27 | + |
| 28 | +endpoint = os.environ.get("APPCONFIGURATION_ENDPOINT_STRING") |
| 29 | +credential = DefaultAzureCredential() |
| 30 | + |
| 31 | + |
| 32 | +async def my_targeting_accessor() -> TargetingContext: |
| 33 | + session_id = "" |
| 34 | + if "Session-ID" in request.headers: |
| 35 | + session_id = request.headers["Session-ID"] |
| 36 | + return TargetingContext(user_id=session_id) |
| 37 | + |
| 38 | + |
| 39 | +# Connecting to Azure App Configuration using AAD |
| 40 | +config = load(endpoint=endpoint, credential=credential, feature_flag_enabled=True, feature_flag_refresh_enabled=True) |
| 41 | + |
| 42 | +# Load feature flags and set up targeting context accessor |
| 43 | +feature_manager = FeatureManager(config, targeting_context_accessor=my_targeting_accessor) |
| 44 | + |
| 45 | + |
| 46 | +@app.before_request |
| 47 | +async def before_request(): |
| 48 | + if "session_id" not in session: |
| 49 | + session["session_id"] = str(uuid.uuid4()) # Generate a new session ID |
| 50 | + request.headers["Session-ID"] = session["session_id"] |
| 51 | + |
| 52 | + |
| 53 | +@app.route("/") |
| 54 | +async def hello(): |
| 55 | + variant = await feature_manager.get_variant("Message") |
| 56 | + return str(variant.configuration if variant else "No variant found") |
| 57 | + |
| 58 | + |
| 59 | +app.run() |
0 commit comments