이 페이지에서

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

실험 Python SDK

Amplitude Experiment의 서버 측 Python SDK 구현에 대한 공식 문서입니다.

이 문서에는 원격 및 로컬 평가에 대한 섹션이 별도로 제공됩니다.

원격 평가

원격 평가를 사용하여 사용자의 변형 가져오기를 구현합니다.

설치

Python 버전 호환성

Python Server SDK는 Python 3.6 이상에서 작동합니다.

pip를 사용하여 Python Server SDK를 설치합니다.

bash
pip install amplitude-experiment

빠른 시작

  1. 실험 클라이언트 초기화
  2. 사용자를 위한 변형 가져오기
  3. 플래그 변형에 액세스
python
from amplitude_experiment import Experiment, RemoteEvaluationConfig, RemoteEvaluationClient, User
# (1) Initialize the experiment client
experiment = Experiment.initialize_remote('<DEPLOYMENT_KEY>')
# (2) Fetch variants for a user
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={
        'premium': True
    }
)
variants = experiment.fetch_v2(user)
# (3) Access a flag's variant
variant = variants['YOUR-FLAG-KEY']
if variant:
    if variant.value == 'on':
        # Flag is on
    else:
        # Flag is off

초기화

서버 시작 시 서버에서 SDK 클라이언트를 초기화합니다.api_key 매개변수에 전달하는 배포 키 인수는 분석 이벤트를 전송하는 동일한 프로젝트 내에 있어야 합니다.

python
Experiment.initialize_remote(api_key, config = None) : RemoteEvaluationClient

시간 초과 및 재시도 구성

성능 요구 사항에 가장 적합한 시간 초과 및 재시도 옵션을 구성하십시오.

python
experiment = Experiment.initialize_remote('<DEPLOYMENT_KEY>', Config())

구성

초기화 시 SDK 클라이언트를 구성할 수 있습니다.

EU 데이터 센터

Amplitude의 EU 데이터 센터를 사용하고 있는 경우, 초기화 시 server_zone 옵션을 구성하십시오.

가져오기

사용자의 변형을 가져오고 결과를 반환합니다. 원격으로 평가 함수는 SDK 클라이언트를 초기화하는 데 사용된 배포와 관련된 플래그에 대해 사용자를 평가합니다.

python
fetch_v2(user: User, fetch_options: FetchOptions = None) : Variants

FetchOptions

python
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={
        'premium': True
    }
)
variants = experiment.fetch_v2(user)

사용자의 변형을 가져온 후에는 특정 플래그의 변형에 액세스할 수도 있습니다.

python
variant = variants['YOUR-FLAG-KEY']
if variant:
    if variant.value == 'on':
        # Flag is on
    else:
        # Flag is off

비동기식 가져오기

fetch 메서드는 동기식입니다. 비동기적으로 가져오려면 fetch_async 메서드를 사용할 수 있습니다.

python
fetch_async_v2(user: User, callback)
python
def fetch_callback(user, variants):
  variant = variants['YOUR-FLAG-KEY']
  if variant:
    if variant.value == 'on':
      # Flag is on
    else:
      # Flag is off
experiment.fetch_async_v2(user, fetch_callback)

지역 평가

로컬 평가를 사용하여 사용자에 대한 변형 평가를 구현합니다. 로컬 평가를 사용하려는 경우 트레이드오프를 이해해야 합니다.

설치

Python Server SDK의 로컬 평가를 설치합니다.

운영 체제 및 아키텍처 지원

로컬 평가 패키지는 다음과 같은 운영 체제 및 아키텍처를 지원합니다(OS/ARCH):

지원됨

  • darwin/amd64
  • darwin/arm64
  • linux/amd64
  • 리눅스/arm64

로컬 평가판 패키지는 Alpine Linux를 지원하지 않습니다.

다른 OS/아키텍처 지원이 필요하다면 github에 이슈를 제출하거나 experiment@amplitude.com으로 이메일을 보내주십시오.

pip를 사용하여 Python Server SDK를 설치합니다.

bash
pip install amplitude-experiment

빠른 시작

  1. 로컬 평가 클라이언트를 초기화합니다.
  2. 로컬 평가 클라이언트를 시작합니다.
  3. 사용자를 평가합니다.
python
# (1) Initialize the local evaluation client with a server deployment key.
experiment = Experiment.initialize_local("DEPLOYMENT_KEY", LocalEvaluationConfig(
  # (Recommended) Enable local evaluation cohort targeting.
  cohort_sync_config=CohortSyncConfig(api_key="API_KEY", secret_key="SECRET_KEY")
))
# (2) Start the local evaluation client.
experiment.start()
# (3) Evaluate a user.
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={
        'premium': True
    }
)
variants = experiment.evaluate_v2(user)

초기화

로컬 평가 클라이언트를 초기화합니다.

서버 배포

키 로컬 평가 플래그 구성에 액세스하려면 서버 배포 키를 사용하여 로컬 평가 클라이언트를 초기화해야 합니다.

python
Experiment.initialize_local(api_key, config = None) : LocalEvaluationClient

플래그 폴링 간격

flag_config_polling_interval_millis 구성 설정을 사용하여 수정 후 플래그 구성이 업데이트되는 데 걸리는 시간을 결정합니다(기본값 30초).

구성

초기화 시 SDK 클라이언트를 구성할 수 있습니다.

EU 데이터 센터

Amplitude의 EU 데이터 센터를 사용하는 경우, 초기화 시 server_zone 옵션을 구성하십시오.

LocalEvaluationConfig

할당설정

ExposureConfig

CohortSyncConfig

시작

로컬 평가 클라이언트를 시작하여 평가를 위한 로컬 평가 모드 플래그 구성을 미리 가져오고 구성된 간격에 따라 플래그 구성 폴러를 시작합니다.

python
start()

evaluate_v2()를 호출하기 전에 플래그 구성을 사용할 준비가 되었는지 확인하려면 start()의 결과를 기다려야 합니다.

python
experiment.start()

평가

start()에서 미리 가져온 플래그를 사용하여 평가 로직을 실행합니다. evaluate에 사용자 객체 인수를 지정해야 합니다. 플래그 변형의 특정 하위 집합만 필요한 경우 선택적으로 플래그 키 배열을 전달할 수 있습니다.

자동 할

당 추적 evaluate_v2()가 호출될 때 assignment_configAmplitude에 할당 이벤트를 자동으로 추적하도록 설정합니다.

노출 추적

노출 추적을 활성화하려면 exposure_config을 설정하십시오. 그런 다음 evaluate_v2()을 호출할 때 EvaluateOptions의 tracks_exposure을 True(으)로 설정하십시오.

python
evaluate_v2(self, user: User, flag_keys: List[str], options: EvaluateOptions) : Dict[str, Variant]
python
# The user to evaluate
user = User(user_id='test_user')
# Evaluate all flag variants
all_variants = experiment.evaluate_v2(user)
# Evaluate a specific subset of flag variants
specific_variants = experiment.evaluate_v2(user, ["<FLAG_KEY_1>", "<FLAG_KEY_2>"])
# Access a variant
variant = all_variants["<FLAG_KEY>"]
if variant.value == 'on':
    # Flag is on
else:
    # Flag is off

평가 옵션

로컬 평가 코호트 타겟팅

버전 1.4.0부터 로컬 평가 SDK 클라이언트는 로컬 평가 타겟팅을 위한 코호트 다운로드를 지원합니다. 이 지원을 활성화하려면 초기화 시 분석 api_key 및 secret_key와 함께 cohort_sync_config 옵션을 구성해야 합니다.

python
experiment = Experiment.initialize_local("DEPLOYMENT_KEY", LocalEvaluationConfig(
  # (Recommended) Enable local evaluation cohort targeting.
  cohort_sync_config=CohortSyncConfig(api_key="API_KEY", secret_key="SECRET_KEY")
))

사용자 지정 로깅

사용자 지정 logging.Logger 인스턴스를 전달하여 로깅 동작을 제어합니다.

사용자 지정 로거

사용자 지정 logging.Logger인스턴스를 RemoteEvaluationConfig또는 에 LocalEvaluationConfig전달하십시오.

python
import logging
from amplitude_experiment import Experiment, RemoteEvaluationConfig, LocalEvaluationConfig
# Create a custom logger
custom_logger = logging.getLogger('MyAppLogger')
custom_logger.setLevel(logging.WARN)
handler = logging.FileHandler('experiment.log')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
custom_logger.addHandler(handler)
# Remote evaluation with custom logger
remote_config = RemoteEvaluationConfig(
    logger=custom_logger
)
experiment = Experiment.initialize_remote('DEPLOYMENT_KEY', remote_config)
# Local evaluation with custom logger
local_config = LocalEvaluationConfig(
    logger=custom_logger
)
experiment = Experiment.initialize_local('DEPLOYMENT_KEY', local_config)

기본 로거를 사용한 디버그 플래그

사용자 지정 로거가 없으면 debug플래그가 기본 로거의 수준을 제어합니다.

python
# Without custom logger, debug=False uses WARNING level
config = RemoteEvaluationConfig(
    debug=False
)
# Default logger level is WARNING
# Without custom logger, debug=True uses DEBUG level
config = RemoteEvaluationConfig(
    debug=True
)
# Default logger level is DEBUG

사용자 지정 로거를 사용하면 SDK가 debug플래그를 무시하고 로거는 구성된 수준을 유지합니다.

python
import logging
from amplitude_experiment import Experiment, RemoteEvaluationConfig
custom_logger = logging.getLogger('MyAppLogger')
custom_logger.setLevel(logging.WARN)
# Custom logger maintains its WARN level regardless of debug flag
config = RemoteEvaluationConfig(
    logger=custom_logger,
    debug=True
)
# Logger level stays WARN (debug flag is ignored)

Amplitude 쿠키에 액세스

클라이언트 측에서 Amplitude 애널리틱스 SDK를 사용하는 경우, Python 서버 SDK는 Amplitude ID 쿠키를 구문 분석하고 상호 작용할 수 있는 편리한 함수를 포함하는 AmplitudeCookie클래스를 제공합니다. 이 기능은 특히 클라이언트가 아직 장치 ID를 생성하지 않은 경우 서버의 장치 ID가 클라이언트에 설정된 장치 ID와 일치하는지 확인하는 데 유용합니다.

python
import uuid
from amplitude_experiment import AmplitudeCookie
# Get the cookie name for the Amplitude API key
# For Browser SDK 2.0 cookies, use new_format=True:
# amp_cookie_name = AmplitudeCookie.cookie_name('amplitude-api-key', new_format=True)
amp_cookie_name = AmplitudeCookie.cookie_name('amplitude-api-key')
device_id = None
# Try to get device ID from existing cookie
if request.cookies.get(amp_cookie_name):
  device_id = AmplitudeCookie.parse(request.cookies.get(amp_cookie_name)).device_id
  # For Browser SDK 2.0: AmplitudeCookie.parse(request.cookies.get(amp_cookie_name), new_format=True).device_id
# If no device ID found, generate a new one and set the cookie
if device_id is None:
  device_id = str(uuid.uuid4())
  amp_cookie_value = AmplitudeCookie.generate(device_id)
  # For Browser SDK 2.0: AmplitudeCookie.generate(device_id, new_format=True)
  response.set_cookie(amp_cookie_name, amp_cookie_value,
    domain='.your-domain.com',  # this should be the same domain used by the Amplitude JS SDK
    httponly=False,
    secure=False
  )

이 내용이 도움이 되었나요?