# Python SDK

> 来源：https://help.gravity-engine.com/docs/server-integration/event-collection/python-sdk
> 介绍 Gravity Engine Python SDK 的环境要求、安装初始化、事件追踪和用户属性管理，并提供参数说明与代码示例。



## 概述 [#概述]

Gravity Engine Python SDK 是一个用于数据采集和上报的工具，帮助开发者轻松集成事件追踪和用户行为分析功能。本 SDK 兼容 Python 3.7 及以上版本。在接入前，请先阅读 [接入前准备](/docs/getting-started)。服务端接入 Python SDK，完成事件的服务端报送功能，您需要注意以下几点：

* 服务端 SDK仅负责事件的收集上报，不负责用户的注册，用户注册需要调用客户端 SDK 的 `initialize` 方法完成；
* 客户端和服务端 SDK使用的用户 `client id` 需要保持一致；
* 在客户端完成 `initialize` 方法调用之后，服务端 SDK才能开始做事件采集上报，否则上报不成功；
* 服务端 SDK接入事件上报时，请参考 [元事件页面](https://web.gravity-engine.com/#/manage/metadata/metaEvent) 下关于事件的详情属性；
* 请尽量上报事件的公共属性，引力不做强制要求，但是上报足够多属性，可以方便您后续在引力平台使用数据分析功能（`$city`、`$province`、`$country`、`$browser`、`$browser_version` 属性可以不上报，引力后端会自动采集）；
* 关于属性的更多信息，请您参考 [事件属性页面](https://web.gravity-engine.com/#/manage/metadata/eventProperty)。

### 1. 环境要求 [#1-环境要求]

* Python 最低兼容 3.7 版本。

### 2. 安装集成 [#2-安装集成]

#### pip 集成 [#pip-集成]

```bash
pip install gravity-python-sdk
```

#### 手动下载 [#手动下载]

下载 PY 文件：[下载地址](https://pypi.org/project/gravity-python-sdk/)

### 3. 初始化配置 [#3-初始化配置]

#### 基础配置 [#基础配置]

```python
from gesdk.sdk import *

GEAnalytics.enableLog(isPrint=True)
GE_ACCESS_TOKEN = 'xxx'
GE_SERVER_MAIN_URL = f'https://backend.gravity-engine.com/event_center/api/v1/event/collect/?access_token={GE_ACCESS_TOKEN}'

consumer = GEDebugConsumer(server_uri=GE_SERVER_MAIN_URL)
ge = GEAnalytics(consumer, strict=True)
```

## 核心功能 [#核心功能]

### 1. 事件追踪 [#1-事件追踪]

> **如需上报自定义事件，您必须先在 [元事件](https://web.gravity-engine.com/#/manage/metadata/metaEvent) 中添加，否则会上报失败！**

您可以调用 `track` 方法，记录用户自定义事件。

您需要先在 [元事件](https://web.gravity-engine.com/#/manage/metadata/metaEvent) 中添加自定义事件，然后调用 `track` 方法上报自定义事件。

```python
event_properties = {
    "$city": "xx",
    "age": 18,
    "name": "hello",
    "array": ["a", "🙂", "😀"]
}

try:
    ge.track(client_id="client_id", event_name="$AppStart", properties=event_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

* 事件的名称是字符串类型。
* Key 为该属性的名称，为字符串类型。
* Value 为该属性的值，支持字符串、数字、布尔、时间、对象、对象组、数组。

### 2. 用户属性管理 [#2-用户属性管理]

#### 设置用户属性（覆盖） [#设置用户属性覆盖]

对于一般的用户属性，您可以调用 `user_set` 进行设置，使用该接口上传的属性将会覆盖原有的属性值。

```python
try:
    user_properties = {"user_name": 'XXX', 'count': 1, 'arr': ['111', '222']}
    ge.user_set(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 初始化用户属性（仅首次设置有效） [#初始化用户属性仅首次设置有效]

对于只在首次设置时有效的属性，我们可以使用 `user_set_once` 记录这些属性。与 `user_set` 方法不同的是，如果被设置的用户属性已存在，则这条记录会被忽略而不会覆盖已有数据。因此，`user_set_once` 适用于为用户设置首次激活时间、首次注册时间等属性。

```python
try:
    user_set_once_properties = {"prop_set_once": "111"}
    ge.user_set_once("client_id", user_set_once_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 累加用户属性 [#累加用户属性]

对于数值型的用户属性，可以使用 `user_increment` 对属性值进行累加。常用于记录用户付费次数、付费额度、积分等属性。

```python
try:
    user_properties = {"total_revenue": 100}
    ge.user_increment(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 用户属性取最大值 [#用户属性取最大值]

对于数值型的用户属性，可以使用 `user_max` 比较数值大小，保存较大的值。

```python
try:
    user_properties = {"total_revenue": 100}
    ge.user_max(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 用户属性取最小值 [#用户属性取最小值]

对于数值型的用户属性，可以使用 `user_min` 比较数值大小，保存较小的值。

```python
try:
    user_properties = {"total_revenue": 10}
    ge.user_min(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 用户属性追加 [#用户属性追加]

对用户喜爱的电影、用户点评过的餐厅等属性，可以调用 `user_append` 记录列表型属性。

```python
try:
    user_properties = {"prop_list_type": ["a", "a"]}
    ge.user_append(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 用户属性去重追加 [#用户属性去重追加]

调用 `user_uniq_append` 对 Array 类型的用户数据去重追加元素。

```python
try:
    user_properties = {"prop_list_type": ["a", "b", "c", "c"]}
    ge.user_uniq_append(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 重置用户属性 [#重置用户属性]

如果需要重置已设置的某个用户属性，可以调用 `user_unset` 进行重置。

```python
try:
    user_properties = {"prop_unset": ""}
    ge.user_unset(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)
```

#### 清空用户属性 [#清空用户属性]

调用 `user_del` 方法，将把当前用户属性清空，您将无法再查询该名用户的用户属性，但该用户产生的事件仍然可以被查询到。

```python
try:
    ge.user_del(client_id="client_id")
except Exception as e:
    raise GEIllegalDataException(e)
```

### 3. 数据管理 [#3-数据管理]

#### 立即上报数据 [#立即上报数据]

```python
ge.flush()
```

> **注意**：频繁调用 `flush()` 会影响性能，建议在重要操作后调用。

#### 关闭 SDK [#关闭-sdk]

```python
ge.close()
```

> 在应用关闭前调用，确保缓存数据不会丢失。

## 完整示例 [#完整示例]

```python
from gesdk.sdk import *

GEAnalytics.enableLog(isPrint=True)
GE_ACCESS_TOKEN = 'xxx'
GE_SERVER_MAIN_URL = f'https://backend.gravity-engine.com/event_center/api/v1/event/collect/?access_token={GE_ACCESS_TOKEN}'

consumer = GEDebugConsumer(server_uri=GE_SERVER_MAIN_URL)
# consumer = GEBatchConsumer(server_uri=GE_SERVER_MAIN_URL, compress=compress, )
# consumer = GEAsyncBatchConsumer(server_uri=GE_SERVER_MAIN_URL)

ge = GEAnalytics(consumer, strict=True)

try:
    user_properties = {"user_name": "xxx", 'count': 1, 'arr': ['111', '222']}
    ge.user_set(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"total_revenue": 100}
    ge.user_increment(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_set_once_properties = {"prop_set_once": "111"}
    ge.user_set_once("client_id", user_set_once_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_set_once_properties = {"prop_set_once": "222"}
    ge.user_set_once("client_id", user_set_once_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"total_revenue": 100}
    ge.user_increment(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"total_revenue": 20000}
    ge.user_max(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"total_revenue": 10}
    ge.user_min(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"prop_list_type": ["a", "a"]}
    ge.user_append(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"prop_list_type": ["a", "b", "c", "c"]}
    ge.user_uniq_append(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"prop_unset": "xxx"}
    ge.user_set(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"prop_unset": ""}
    ge.user_unset(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"user_name": "py-name"}
    ge.user_set(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    user_properties = {"user_name": ""}
    ge.user_unset(client_id="client_id", properties=user_properties)
except Exception as e:
    raise GEIllegalDataException(e)

try:
    ge.user_del(client_id="client_id")
except Exception as e:
    raise GEIllegalDataException(e)

try:
    event_properties = {
         "$city": "xx",
         "age": 18,
         "name": "hello",
         "array": ["a", "🙂", "😀"]
     }
    ge.track(client_id="client_id", event_name="$AppStart", properties=event_properties)
except Exception as e:
    raise GEIllegalDataException(e)

ge.flush()
ge.close()
```

## 最佳实践 [#最佳实践]

1. **异常处理**：对所有 SDK 调用进行异常捕获。
2. **资源清理**：在应用关闭前调用 `close()` 方法。
3. **属性命名**：使用有意义的属性名称，保持一致性。
4. **数据类型**：确保属性值类型符合预期，避免类型错误。

## 故障排除 [#故障排除]

### 常见问题 [#常见问题]

1. **初始化问题**：检查 `ACCESS_TOKEN` 和服务器地址是否正确
2. **数据格式**: 验证事件属性数据类型是否符合要求
3. **性能问题**: 避免频繁调用 `flush()` 方法
