이 페이지에서

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.

Ampli for Python SDK

Amplitude 데이터는 Python 앱(Python 3.6 이상)의 분석 이벤트 추적을 지원합니다. Ampli는 생성된 추적 라이브러리를 Python 패키지로 패키징합니다.

  1. Amplitude SDK 설치

    shell
    pip install amplitude-analytics
    
  2. Ampli CLI 설치

    shell
    npm install -g @amplitude/ampli
    
  3. Ampli 래퍼를 프로젝트에 가져오십시오

    shell
    ampli pull [--path ./ampli]
    
  4. Ampli 래퍼 초기화

    python
    from .ampli import *
    ampli.load(LoadOptions(
      client=LoadClientOptions(AMPLITUDE_API_KEY)
    ))
    
  5. 사용자 식별 및 사용자 속성 설정

    python
    ampli.identify("user_id", Identify(userProp="A trait associated with this user"))
    
  6. 강력하게 유형화된 메소드 및 클래스를 사용하여 이벤트 추적

    python
    ampli.song_played('user_id', SongPlayed(song_id="song-1"))
    ampli.track('user-id', new SongFavorited(song_id="song-2"));
    
  7. 애플리케이션 종료 전 이벤트 플러시

    python
    ampli.flush();
    
  8. CLI를 사용하여 구축 상태 확인

    shell
    ampli status [--update]
    

Amplitude SDK 설치

아직 설치하지 않은 경우 핵심 Amplitude SDK 의존성을 설치하십시오.

bash
pip install amplitude-analytics

Ampli 설치

Ampli CLI는 Homebrew 또는 NPM에서 설치할 수 있습니다.

npm install -g @amplitude/ampli

Ampli 래퍼를 프로젝트에 가져오기

프로젝트 루트 디렉토리에서 Ampli CLI pull 명령을 실행하여 Amplitude 데이터에 로그인하고 추적 계획을 위한 강력한 형식의 Ampli 래퍼를 다운로드하십시오.

bash
ampli pull

Ampli는 작업 공간에 로그인하고 소스를 선택하라는 메시지를 표시합니다.

bash
➜ ampli pull
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
? Organization: Amplitude
? Workspace: My Workspace
? Source: My Source

Ampli 초기화

코드에서 Ampli를 초기화하십시오. load() 메서드에는 Ampli 래퍼의 구성 옵션을 지정하는 LoadOptions 인스턴스가 필요합니다.

python
from .ampli import *
ampli.load(LoadOptions(
   client=LoadClientOptions(AMPLITUDE_API_KEY)
))

LoadOptions는 다음 인수를 허용합니다.

LoadClientOptions는 다음 인수를 허용합니다.

Identify

identify()를 호출하여 앱에서 사용자를 식별하거나, 향후 발생할 모든 이벤트를 해당 ID와 연관시키거나, 해당 사용자 속성을 설정하십시오. Ampli는 추적 계획에서 사용자 속성에 대한 유형을 생성합니다.

identify() 함수는 문자열user_id, Identify 이벤트 인스턴스 및 선택적인 EventOptions을 허용합니다.

예를 들어, 추적 계획에 role 문자열 유형의 사용자 속성이 포함된 경우:

python
ampli.identify("user_id", Identify(role="admin"))

options 인수는 이 호출에 대해 device_id와 같은 Amplitude 필드를 허용합니다.

python
ampli.identify("user_id", Identify(role="admin"), EventOptions(device_id="device_id"))

그룹 식별

앱에서 그룹을 식별하고 그룹 속성을 설정하거나 업데이트하려면 group_identify() 호출하십시오. Ampli는 추적 계획에서 그룹 속성에 대한 유형을 생성합니다.

이 group_identify() 함수는 문자열 group_type, 문자열 group_name, Group 이벤트 인스턴스 및 선택 사항인 EventOptions을 허용합니다.

예를 들어, 추적 계획에 정수 유형의 total_member속성을 가진 그룹sport:football이 포함된 경우:

python
ampli.group_identify("sport", "football", Group(total_member=23))

그룹 설정

사용자를 자신의 그룹(예: 부서 또는 회사)과 연결하기 위해 set_group()호출합니다. set_group() 함수는 user_id, group_type, group_name 및 선택 사항인 EventOptions을 허용합니다.

python
ampli.set_group("user_id", "sport", "football")

group_name 는 단일 그룹 이름 문자열 또는 여러 그룹 이름 목록을 허용합니다.

python
ampli.set_group("user_id", "sport", ["football", "basketball"])

추적

이벤트를 추적하려면 이벤트에 해당하는 함수를 호출하십시오. 추적 계획의 모든 이벤트는 Ampli 래퍼에서 고유한 함수를 갖습니다. 다음과 같이 호출을 구성하십시오.

python
ampli.event_name("user_id", EventName(...), EventOptions(...))

선택적 EventOptions인수는 device_id와 같은 Amplitude 필드를 허용합니다.

예를 들어, 추적 계획에 두 개의 필수 속성인 songId(문자열) 및 songFavorited(부울)을 포함하는 songPlayed라는 이벤트가 포함되어 있는 경우:

python
ampli.song_played('user_id', SongPlayed(
  song_id = 'songId', # str,
  song_favorited = True, # bool
))

또한 Ampli는 각 이벤트에 대한 클래스를 생성합니다. 일반 트랙 메서드를 사용하여 이벤트 객체를 전송합니다.

python
my_event = SongPlayed(
  song_id = 'songId', # str,
  song_favorited = True, # bool
)
ampli.track('user_id', SongPlayed(
  song_id = 'songId', # str,
  song_favorited = True, # bool
), EventOptions(device_id="device_id"))

플러시

Ampli 래퍼는 이벤트를 대기열에 넣고 flushQueueSize 및 flushInterval 구성 값을 기반으로 자동으로 전송합니다.

보류 중인 모든 이벤트를 즉시 전송하려면 flush()를 호출하십시오. 이 flush() 메서드는 계속하기 전에 보류 중인 모든 이벤트가 전송되도록 보장하는 데 사용할 수 있는 프로미스를 반환합니다. 애플리케이션이 종료되기 전에 flush()를 호출하십시오.

python
ampli.flush();

플러그인

플러그인은 Amplitude의 동작을 확장합니다. 예를 들어 보강 플러그인은 이벤트 속성을 수정하고 목적지 플러그인은 데이터를 타사 API로 전송합니다.

먼저, 플러그인을 정의합니다. 다음 예제에서는 목적지 플러그인을 보여 줍니다.

python
from amplitude import DestinationPlugin, PluginType, BaseEvent, IdentifyEvent
from analytics import Client as SegmentClient
class SegmentPlugin(DestinationPlugin):
  def __init__(self, write_key):
      self.plugin_type = PluginType.DESTINATION
      self.configuration = None
      self.segment = SegmentClient(write_key)
  def setup(self, client):
      self.configuration = client.configuration
  def execute(self, event: BaseEvent) -> None:
      if isinstance(event, IdentifyEvent):
          self.segment.identify(event.user_id, event.user_properties)
      elif isinstance(event, BaseEvent):
          self.segment.track(event.user_id, event.event_type, event.event_properties)

Ampli를 초기화한 후 플러그인을 추가하십시오:

python
ampli.client.add(SegmentPlugin("write_key"))

상태

코드가 status 명령을 사용하여 이벤트를 구현하는지 확인합니다:

bash
ampli status [--update]

출력에는 상태가 표시되고 누락된 이벤트가 표시됩니다.

bash
➜ ampli status
✘ Verifying event tracking implementation in source code
 ✔ Song Played (1 location)
 ✘ Song Stopped Called when a user stops playing a song.
Events Tracked: 1 missed, 2 total

문제 해결

ImportError: 알려진 상위 패키지가 없는 상대 가져오기를 시도했습니다.

이 오류는 python3 main.py와 함께 스크립트를 직접 실행하고 from .ampli import *와 같은 상대 가져오기를 사용할 때 발생합니다. 파이썬은 스크립트를 직접 실행할 때 모듈 구조를 인식하지 못합니다.

두 가지 해결책이 있습니다.

옵션 1: 절대 가져오기 사용

패키지 구조에 따라 절대 가져오기를 사용하십시오.

python
from ampli import *

또는 Ampli 래퍼가 패키지에 들어 있는 경우:

python
from your_package.ampli import *

옵션 2: 모듈로 실행

스크립트를 모듈로 실행하십시오.

bash
python3 -m your_package.main

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