Get started with the Python SDK
이 페이지는 아직 귀하의 언어로 번역되지 않았습니다. 현재 작업 중이므로 곧 다시 확인해 주십시오.
This guide helps you install the Amplitude Python SDK (amplitude-analytics), create a client, and send one event to Amplitude from a server, script, or worker. Each step lists the problems that commonly break it, so you can fix a problem where it happens. For the full option list, go to Configuration options. For changes between versions, go to the Amplitude-Python changelog.
Prerequisites
- An Amplitude project and its API key. To find the key, go to Settings > Projects, select your project, and open General.
- The data center your organization uses: US (default) or EU.
- Python 3.6 or later. The package declares
python_requires=">=3.6, <4"and has no third-party dependencies. - Outbound HTTPS access from your server to
api2.amplitude.com(US) orapi.eu.amplitude.com(EU).
Install the SDK
Install the package with the tool your project uses. The distribution name is amplitude-analytics, and the module you import is amplitude.
pip install amplitude-analytics
Fix installation problems
| Symptom | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'amplitude' | You installed the package in a different environment from the one that runs your code. | Install with the interpreter that runs your app: python -m pip install amplitude-analytics. |
ImportError: cannot import name 'Amplitude' from partially initialized module 'amplitude' | A file named amplitude.py in your project shadows the package. | Rename the file, and delete any __pycache__/amplitude*.pyc next to it. |
Initialize the SDK
Create one Amplitude client per process and reuse it for every request. Each client starts its own background threads, which batch events and upload them.
from amplitude import Amplitude
client = Amplitude("AMPLITUDE_API_KEY")
If your project uses the EU data center, pass Config(server_zone="EU") as the second argument. Go to Choose a data region.
The SDK reports problems through Python's standard logging module, on the logger named amplitude. By default, Python shows only WARNING and higher messages. To see each upload result while you set up the SDK, turn on INFO:
import logging
logging.basicConfig(level=logging.INFO)
Fix initialization problems
| Symptom | Cause | Fix |
|---|---|---|
Log line Invalid API Key, and your callback never runs | The API key is wrong, or server_zone doesn't match the project's data center. | Copy the key again. Set server_zone="EU" for EU projects, and omit it for US projects. |
| No log output from the SDK | No logging handler shows INFO messages. | Call logging.basicConfig(level=logging.INFO), or attach a handler to logging.getLogger("amplitude"). |
| Each request or task creates a new client | Your code builds the client inside a request handler or task function. | Build the client once at module level or app startup, and import it where you need it. |
Send a first event
Track one event for a user, then shut the client down. shutdown() sends every queued event and waits for the upload to finish. Call it at the end of a short script. A long-running server keeps the client open instead. Pass a callback to see the upload result for each event.
from amplitude import Amplitude, BaseEvent, Config
def on_result(event, code, message):
print(event.event_type, code, message)
client = Amplitude("AMPLITUDE_API_KEY", Config(callback=on_result))
client.track(
BaseEvent(
event_type="Sign Up Completed",
user_id="user-12345",
event_properties={"plan": "starter"},
)
)
client.shutdown()
# Sign Up Completed 200 Event sent successfully.
Every event needs a user_id or a device_id, and Amplitude rejects IDs shorter than five characters. Without a shutdown() call, the SDK still flushes when the interpreter exits normally, because the SDK registers shutdown() as an exit handler.
Fix upload problems
The callback receives an integer code and a string message. Some problems never reach the callback, so the first column also lists log lines.
code and message, or log line | Cause | Fix |
|---|---|---|
200, Event sent successfully. | Amplitude accepted the event. | None. Go to Confirm the event in Amplitude. |
400, Invalid id length for user_id or device_id | The user_id or device_id is shorter than five characters. | Use longer IDs, or set min_id_length to the shortest length you send. |
-1, Event reached max retry times 12. | The request never reached Amplitude: no network, DNS failure, a firewall, or a wrong server_url. The SDK gave up after 12 failed attempts. | Check that the host can reach https://api2.amplitude.com, or api.eu.amplitude.com for EU projects. If you set server_url, check the URL. |
Log line Invalid API Key, and no callback | The key is wrong or belongs to a project in the other data center. | Copy the key again and check server_zone. |
Log line Invalid event body {...} with an InvalidEventError traceback | The event has neither user_id nor device_id, or its event_type is empty. | Set user_id or device_id on the event or in its EventOptions, and pass a non-empty event_type. |
Log line Skipped event for opt out config | client.configuration.opt_out is True, or you called track() after shutdown(). | Set opt_out to False, and track events before you shut the client down. |
Log line Consumer thread error with RuntimeError: cannot schedule new futures after shutdown | The process exited while events were still retrying, for example because Amplitude or your proxy was unreachable. The SDK drops those events. | Make sure the host can reach the upload URL. In a script, call client.flush() and wait on the result well before exit, so failures retry while the client is still running. |
| No callback and no log line | The process ended without running exit handlers, for example through os._exit(), SIGKILL, or a frozen serverless container. | Call client.flush() and wait for it before the process stops. Go to Flush before the process exits. |
Confirm the event in Amplitude
- In Amplitude, open User Lookup and search for the user ID you sent,
user-12345in this example. - Open the Activity tab and turn on Live event updates.
- Confirm that
Sign Up Completedappears with theplanproperty.
If the event doesn't appear within a minute, follow Verify events. That guide walks through each stage between track() and Amplitude's servers.
Next steps
- Add the events and properties your tracking plan needs. Go to Track events.
- Update user and group properties with
Identify. - Make sure events survive process shutdown in serverless and short-lived processes.
- Tune batching, retries, and logging in Data delivery.
이 내용이 도움이 되었나요?
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.