Python
This guide describes how to integrate the Python SDK into your project.
Latest version: v3.0.0
Update time: 2023-10-07
Downloads: Source code
This document applies to v3.0.0 and later. For earlier versions, see Python SDK integration guide (V2)
1. Integrate the SDK
- Use
pipto get the Python SDK
pip install ThinkingDataSdk
Upgrade command:
pip install --upgrade ThinkingDataSdk
- Install Logbus
We recommend using SDK + LogBus to collect and report server-side data. To install Logbus, see the following document: LogBus user guide
2. Initialization
The following sample code initializes the SDK:
from tgasdk.sdk import *
consumer = TDLogConsumer("LOG_DIRECTORY", rotate_mode=TD_ROTATE_MODE.HOURLY, file_prefix="LOG_FILE_PREFIX")
te = TDAnalytics(consumer)
LOG_DIRECTORY is the path of the local folder that data is written to. Set the folder that LogBus monitors to this path, and LogBus monitors and uploads the data.
LOG_FILE_PREFIX is the prefix of the log file name.
3. Common features
To make sure that the distinct ID and account ID can be bound correctly, if your game uses both the distinct ID and the account ID, we strongly recommend that you upload both IDs. Otherwise, accounts may fail to match and users may be counted more than once. For details on ID binding rules, see User identification rules.
3.1 Send events
You can call track to upload events. We recommend setting event properties and the conditions for sending events based on the document you prepared earlier. The following sample code sends an event:
distinct_id = "ABCDEF123456"
account_id = "TE10001"
properties = {
"#time": datetime.datetime.now(),
# Set the time when this event occurred. If not set, the current time is used by default
"#ip": "192.168.1.1",
# Set the user's IP. tda automatically resolves the province and city from this IP
# "#uuid":uuid.uuid1(),# Optional. Not needed if the enable_uuid switch above is turned on
"Product_Name": "Product name",
"Price": 30,
"OrderId": "Order abc_123"
}
# Upload an event with both the account ID and the distinct ID
try:
te.track(distinct_id, account_id, "Payment", properties)
# You can also upload only the distinct ID
# te.track(distinct_id = distinct_id, event_name = "Payment", properties = properties)
# Or upload only the account ID
# te.track(account_id = account_id, event_name = "Payment", properties = properties)
except Exception as e:
# Exception handling
print(e)
- The event name is of the string type. It must start with a letter, can contain digits, letters, and underscores "_", and can be up to 50 characters long.
- Key is the name of the property and is of string type. It must start with a letter, can contain digits, letters, and underscores "_", can be up to 50 characters long, and is case-insensitive. AE converts it to lowercase
- Value is the value of the property. Supported types are string, number, Boolean, time, object, object group, and array
User properties have the same requirements as event properties
3.2 Set user properties
For general user properties, you can call user_set to set them. Properties uploaded through this API overwrite the original values. If the user property doesn't exist yet, it is created with the same type as the value passed in. The following example sets the username:
properties = {"user_name": "ABC"}
# Upload user properties. The value of "user_name" is "ABC"
try:
te.user_set(account_id="account_id", distinct_id="distinct_id", properties=properties)
except Exception as e:
# Exception handling
print(e)
3.3 Send data
When you use TDLogConsumer, collected events are first converted to JSON strings and then added to a buffer array. Data is written to disk only when the number of elements in the array exceeds the configured capacity. The default capacity is 5 records. You can set buffer_size in the TDLogConsumer constructor.
In some business scenarios, if you want data to be reported to the AE server immediately, you can call flush(). Note that calling flush() frequently degrades service performance.
te.flush();
3.4 Shut down the SDK
te.close()
Shuts down and exits the SDK. Call this API before you shut down the server to avoid losing data in the cache
4. Best practices
The following sample code includes all of the operations above. We recommend using them in the following order:
from tgasdk.sdk import *
# Initialize the SDK
te = TDAnalytics(TDLogConsumer("LOG_DIRECTORY"))
# Upload an event. The account ID and the distinct ID cannot both be empty
properties = {
"#time": datetime.datetime.now(), # Set the time when this event occurred. If not set, the current time is used by default
"#ip": "192.168.1.1", # Set the user's IP. tda automatically resolves the province and city from this IP
"Product_Name": "Product name"
}
try:
te.track("distinct_id", "account_id", "Payment", properties)
except Exception as e:
# Exception handling
print(e)
# Upload user properties. The value of "user_name" is "ABC"
user_properties = {"user_name": "ABC"}
try:
te.user_set(account_id="account_id", distinct_id="distinct_id", properties=user_properties)
except Exception as e:
# Exception handling
print(e)
# Calling flush writes data to the file immediately. In production, avoid calling flush frequently, which can cause I/O or network overhead
te.flush()

