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 패키지로 패키징합니다.
- shell
pip install amplitude-analytics - shell
npm install -g @amplitude/ampli - shell
ampli pull [--path ./ampli] - python
from .ampli import * ampli.load(LoadOptions( client=LoadClientOptions(AMPLITUDE_API_KEY) )) - python
ampli.identify("user_id", Identify(userProp="A trait associated with this user")) 강력하게 유형화된 메소드 및 클래스를 사용하여 이벤트 추적
pythonampli.song_played('user_id', SongPlayed(song_id="song-1")) ampli.track('user-id', new SongFavorited(song_id="song-2"));- python
ampli.flush(); - shell
ampli status [--update]
Amplitude SDK 설치
아직 설치하지 않은 경우 핵심 Amplitude SDK 의존성을 설치하십시오.
pip install amplitude-analytics
Ampli 설치
Ampli CLI는 Homebrew 또는 NPM에서 설치할 수 있습니다.
npm install -g @amplitude/ampli
Ampli 래퍼를 프로젝트에 가져오기
프로젝트 루트 디렉토리에서 Ampli CLI pull 명령을 실행하여 Amplitude 데이터에 로그인하고 추적 계획을 위한 강력한 형식의 Ampli 래퍼를 다운로드하십시오.
ampli pull
Ampli는 작업 공간에 로그인하고 소스를 선택하라는 메시지를 표시합니다.
➜ 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 인스턴스가 필요합니다.
from .ampli import *
ampli.load(LoadOptions(
client=LoadClientOptions(AMPLITUDE_API_KEY)
))
LoadOptions는 다음 인수를 허용합니다.
| 인수 | 필수 | 기본값 | 설명 |
|---|---|---|---|
disabled | 아니요 | False | True인 경우 모든 Ampli 래퍼 호출은 아무 작업도 수행하지 않습니다. 로컬 또는 개발 환경에서 유용합니다. |
client | 아니요 | None | Amplitude 코어 SDK 클라이언트의 구성 옵션을 지정하는 LoadClientOptions 인스턴스입니다. |
LoadClientOptions는 다음 인수를 허용합니다.
| 인수 | 필수 | 기본값 | 설명 |
|---|---|---|---|
instance | api_key이 설정되지 않은 경우 필수 | 없음 | 사용할 Amplitude 인스턴스입니다. 기본적으로 Ampli는 인스턴스를 생성합니다. |
api_key | instance이 설정되지 않은 경우 필수 | 없음 | 사용할 API 키입니다. 추적 계획에 설정된 API 키를 재정의합니다. |
configuration | 아니요 | None | 사용할 Amplitude 구성입니다. 기본 구성을 재정의합니다. |
Identify
identify()를 호출하여 앱에서 사용자를 식별하거나, 향후 발생할 모든 이벤트를 해당 ID와 연관시키거나, 해당 사용자 속성을 설정하십시오. Ampli는 추적 계획에서 사용자 속성에 대한 유형을 생성합니다.
identify() 함수는 문자열user_id, Identify 이벤트 인스턴스 및 선택적인 EventOptions을 허용합니다.
예를 들어, 추적 계획에 role 문자열 유형의 사용자 속성이 포함된 경우:
ampli.identify("user_id", Identify(role="admin"))
options 인수는 이 호출에 대해 device_id와 같은 Amplitude 필드를 허용합니다.
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이 포함된 경우:
ampli.group_identify("sport", "football", Group(total_member=23))
그룹 설정
사용자를 자신의 그룹(예: 부서 또는 회사)과 연결하기 위해 set_group()호출합니다. set_group() 함수는 user_id, group_type, group_name 및 선택 사항인 EventOptions을 허용합니다.
ampli.set_group("user_id", "sport", "football")
group_name 는 단일 그룹 이름 문자열 또는 여러 그룹 이름 목록을 허용합니다.
ampli.set_group("user_id", "sport", ["football", "basketball"])
추적
이벤트를 추적하려면 이벤트에 해당하는 함수를 호출하십시오. 추적 계획의 모든 이벤트는 Ampli 래퍼에서 고유한 함수를 갖습니다. 다음과 같이 호출을 구성하십시오.
ampli.event_name("user_id", EventName(...), EventOptions(...))
선택적 EventOptions인수는 device_id와 같은 Amplitude 필드를 허용합니다.
예를 들어, 추적 계획에 두 개의 필수 속성인 songId(문자열) 및 songFavorited(부울)을 포함하는 songPlayed라는 이벤트가 포함되어 있는 경우:
ampli.song_played('user_id', SongPlayed(
song_id = 'songId', # str,
song_favorited = True, # bool
))
또한 Ampli는 각 이벤트에 대한 클래스를 생성합니다. 일반 트랙 메서드를 사용하여 이벤트 객체를 전송합니다.
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()를 호출하십시오.
ampli.flush();
플러그인
플러그인은 Amplitude의 동작을 확장합니다. 예를 들어 보강 플러그인은 이벤트 속성을 수정하고 목적지 플러그인은 데이터를 타사 API로 전송합니다.
먼저, 플러그인을 정의합니다. 다음 예제에서는 목적지 플러그인을 보여 줍니다.
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를 초기화한 후 플러그인을 추가하십시오:
ampli.client.add(SegmentPlugin("write_key"))
상태
코드가 status 명령을 사용하여 이벤트를 구현하는지 확인합니다:
ampli status [--update]
출력에는 상태가 표시되고 누락된 이벤트가 표시됩니다.
➜ 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: 절대 가져오기 사용
패키지 구조에 따라 절대 가져오기를 사용하십시오.
from ampli import *
또는 Ampli 래퍼가 패키지에 들어 있는 경우:
from your_package.ampli import *
옵션 2: 모듈로 실행
스크립트를 모듈로 실행하십시오.
python3 -m your_package.main
이 내용이 도움이 되었나요?