> For the complete documentation index, see [llms.txt](https://docs.catfee.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.catfee.io/getting-started/buy-energy-via-api-on-catfee/python.md).

# Python 调用示例

### **前提条件**

1. [您需要一个有效的 API Key 和 API Secret](/getting-started/buy-energy-via-api-on-catfee/api-overview.md#apply-api-info)。
2. 确保您的环境已安装 `requests` 库，可以使用以下命令安装：

   ```
   pip install requests
   ```
3. 使用 Python 3.6 及以上版本。

### **示例代码**

```python
import hashlib
import hmac
import base64
import time
import requests
from urllib.parse import urlencode

API_KEY = "your_api_key"  # 请替换为您的API Key
API_SECRET = "your_api_secret"  # 请替换为您的API Secret
BASE_URL = "https://api.catfee.io"

def generate_timestamp():
    """生成当前的时间戳（ISO 8601格式）"""
    return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())

def build_request_path(path, query_params):
    """构建请求路径，包括查询参数"""
    if not query_params:
        return path
    query_string = urlencode(query_params)
    return f"{path}?{query_string}"

def generate_signature(timestamp, method, request_path):
    """生成签名"""
    sign_string = timestamp + method + request_path
    return hmac_sha256(sign_string, API_SECRET)

def hmac_sha256(data, secret):
    """使用 HMAC-SHA256 算法生成签名"""
    return base64.b64encode(hmac.new(secret.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).digest()).decode()

def create_request(url, method, timestamp, signature):
    """创建 HTTP 请求"""
    headers = {
        "Content-Type": "application/json",
        "CF-ACCESS-KEY": API_KEY,
        "CF-ACCESS-SIGN": signature,
        "CF-ACCESS-TIMESTAMP": timestamp,
    }
    
    if method == "POST":
        response = requests.post(url, headers=headers)
    elif method == "GET":
        response = requests.get(url, headers=headers)
    elif method == "PUT":
        response = requests.put(url, headers=headers)
    elif method == "DELETE":
        response = requests.delete(url, headers=headers)
    else:
        raise ValueError(f"Unsupported HTTP method: {method}")
    
    return response

def main():
    method = "POST"  # 可以修改为 "GET", "PUT", "DELETE" 等方法
    path = "/v1/order"
    
    # 示例：创建订单
    query_params = {
        "quantity": "65000",
        "receiver": "TRON_ADDRESS",
        "duration": "1h"
    }
    
    # 生成请求头
    timestamp = generate_timestamp()
    request_path = build_request_path(path, query_params)
    signature = generate_signature(timestamp, method, request_path)
    
    # 创建请求 URL
    url = BASE_URL + request_path
    
    # 发送请求
    response = create_request(url, method, timestamp, signature)
    
    # 打印响应
    print("Response Code:", response.status_code)
    print("Response Body:", response.text)
    
    # 处理可能的错误信息
    if response.status_code != 200:
        print("Error:", response.json())

if __name__ == "__main__":
    main()
```

### **代码解析**

1. **`generate_timestamp()`**：\
   生成当前的 UTC 时间戳（ISO 8601 格式）。使用 `time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())` 生成时间戳。
2. **`build_request_path()`**：\
   该函数接收 `path` 和查询参数（`query_params`），并构建包含查询参数的完整请求路径。如果没有查询参数，直接返回 `path`。
3. **`generate_signature()`**：\
   使用 `timestamp`、`method` 和 `request_path` 拼接成签名字符串，然后调用 `hmac_sha256()` 来生成签名。
4. **`hmac_sha256()`**：\
   使用 HMAC-SHA256 算法生成签名，使用 API Secret 作为密钥进行加密，并对结果进行 Base64 编码。
5. **`create_request()`**：\
   根据 HTTP 方法（`POST`、`GET`、`PUT`、`DELETE`）发送请求。通过 `requests` 库创建 HTTP 请求并返回响应。
6. **`main()`**：\
   在 `main()` 函数中，设置请求方法为 `POST`，构建查询参数，生成时间戳、签名和请求路径，最终发送请求并打印响应。

### **注意事项**

* **API Key 和 Secret**：\
  请确保将 `API_KEY` 和 `API_SECRET` 替换为您从 CatFee.IO 获取的实际值。
* **错误处理**：\
  示例代码中处理了请求失败的情况，如果响应码不为 `200`，会打印错误信息。
* **请求方法**：\
  支持 `POST`、`GET`、`PUT` 和 `DELETE` 请求，您可以根据实际需求修改请求方法。

### **总结**

此示例展示了如何使用 Python 调用 CatFee.IO Rest API，利用 HMAC-SHA256 签名确保请求的安全性。您可以根据需要调整代码，支持 `GET`、`POST`、`PUT` 和 `DELETE` 等 HTTP 方法。
