pytbox 20250818.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pytbox might be problematic. Click here for more details.

@@ -0,0 +1,7 @@
1
+ """
2
+ Common utilities and base classes
3
+ """
4
+
5
+ from .base import BaseAPI, BaseResponse
6
+
7
+ __all__ = ["BaseAPI", "BaseResponse"]
pytbox/common/base.py ADDED
@@ -0,0 +1,44 @@
1
+ """
2
+ Base classes and common utilities
3
+ """
4
+
5
+ from ..utils.timeutils import TimeUtils
6
+ from typing import Dict, Any
7
+ import json
8
+
9
+
10
+ class BaseAPI:
11
+ """API基类,提供通用功能"""
12
+
13
+ def __init__(self, base_url: str = ""):
14
+ self.base_url = base_url
15
+ self._session_created_at = TimeUtils.get_timestamp()
16
+
17
+ def get_session_age(self) -> int:
18
+ """获取会话存活时间(秒)"""
19
+ current_time = TimeUtils.get_timestamp()
20
+ return current_time - self._session_created_at
21
+
22
+ def log_request(self, method: str, url: str, data: Dict[Any, Any] = None) -> str:
23
+ """记录请求日志"""
24
+ timestamp = TimeUtils.get_timestamp()
25
+ log_entry = {
26
+ "timestamp": timestamp,
27
+ "method": method,
28
+ "url": url,
29
+ "data": data or {}
30
+ }
31
+ return json.dumps(log_entry, ensure_ascii=False)
32
+
33
+
34
+ class BaseResponse:
35
+ """响应基类"""
36
+
37
+ def __init__(self, data: Dict[Any, Any]):
38
+ self.data = data
39
+ self.created_at = TimeUtils.get_timestamp()
40
+
41
+ def is_expired(self, ttl_seconds: int = 3600) -> bool:
42
+ """检查响应是否过期"""
43
+ current_time = TimeUtils.get_timestamp()
44
+ return (current_time - self.created_at) > ttl_seconds
pytbox/dida365.py ADDED
File without changes
pytbox/timeutils.py ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env python3
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Optional
5
+
6
+
7
+ @dataclass
8
+ class ReturnResponse:
9
+ """统一响应格式类
10
+
11
+ Attributes:
12
+ code: 响应状态码
13
+ 0 - 成功 (SUCCESS)
14
+ 1 - 一般错误 (ERROR)
15
+ 2 - 警告 (WARNING)
16
+ 3 - 未授权 (UNAUTHORIZED)
17
+ 4 - 资源未找到 (NOT_FOUND)
18
+ 5 - 请求超时 (TIMEOUT)
19
+ 6 - 参数错误 (INVALID_PARAMS)
20
+ 7 - 权限不足 (PERMISSION_DENIED)
21
+ 8 - 服务不可用 (SERVICE_UNAVAILABLE)
22
+ 9 - 数据库错误 (DATABASE_ERROR)
23
+ 10 - 网络错误 (NETWORK_ERROR)
24
+ message: 响应消息描述
25
+ data: 响应数据,可以是任意类型
26
+ """
27
+ code: int = 0
28
+ msg: str = ''
29
+ data: Optional[Any] = None
30
+
31
+ def is_success(self) -> bool:
32
+ """判断是否为成功响应
33
+
34
+ Returns:
35
+ bool: code为0时返回True,否则返回False
36
+ """
37
+ return self.code == 0
38
+
39
+ def is_error(self) -> bool:
40
+ """判断是否为错误响应
41
+
42
+ Returns:
43
+ bool: code不为0时返回True,否则返回False
44
+ """
45
+ return self.code != 0
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env python3
2
+
3
+
4
+ import time
5
+
6
+
7
+ class TimeUtils:
8
+
9
+ @staticmethod
10
+ def get_timestamp(now: bool=True) -> int:
11
+ '''
12
+ 获取时间戳
13
+
14
+ Args:
15
+ now (bool, optional): _description_. Defaults to True.
16
+
17
+ Returns:
18
+ _type_: _description_
19
+ '''
20
+ if now:
21
+ return int(time.time())
22
+ else:
23
+ return int(time.time() * 1000)
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import requests
4
+ from .utils.response import ReturnResponse
5
+
6
+
7
+ class VictoriaMetrics:
8
+
9
+ def __init__(self, url: str='', timeout: int=3) -> None:
10
+ self.url = url
11
+ self.timeout = timeout
12
+ self.session = requests.Session()
13
+ self.session.headers.update({
14
+ 'Content-Type': 'application/json',
15
+ 'Accept': 'application/json'
16
+ })
17
+
18
+ def query(self, query: str) -> ReturnResponse:
19
+ '''
20
+ 查询指标数据
21
+
22
+ Args:
23
+ query (str): 查询语句
24
+
25
+ Returns:
26
+ dict: 查询结果
27
+ '''
28
+ url = f"{self.url}/prometheus/api/v1/query"
29
+ r = requests.get(
30
+ url,
31
+ timeout=self.timeout,
32
+ params={"query": query}
33
+ )
34
+ if r.json().get("status") == "success":
35
+ return ReturnResponse(code=0, msg=f"[{query}] 查询成功!", data=r.json()['data']['result'])
36
+ else:
37
+ return ReturnResponse(code=1, msg=f"[{query}] 查询失败: {r.json().get('error')}", data=r.json())
@@ -0,0 +1,262 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytbox
3
+ Version: 20250818.2
4
+ Summary: A collection of Python integrations and utilities (Feishu, Dida365, VictoriaMetrics, ...)
5
+ Author-email: mingming hou <houm01@foxmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: requests>=2.0
10
+ Requires-Dist: pydantic>=1.10
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest; extra == "dev"
13
+ Requires-Dist: black; extra == "dev"
14
+ Requires-Dist: ruff; extra == "dev"
15
+ Requires-Dist: python-dotenv; extra == "dev"
16
+
17
+ # PytBox
18
+
19
+ [![PyPI version](https://img.shields.io/pypi/v/pytbox.svg)](https://pypi.org/project/pytbox/)
20
+ [![Python version](https://img.shields.io/pypi/pyversions/pytbox.svg)](https://pypi.org/project/pytbox/)
21
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
22
+
23
+ 一个集成了多种服务和实用工具的 Python 包,专为运维开发场景设计。包含 VictoriaMetrics、滴答清单(Dida365)、飞书等服务的集成工具,以及常用的时间处理等实用工具。
24
+
25
+ ## 特性
26
+
27
+ - 🔍 **VictoriaMetrics 集成** - 提供时序数据库查询功能
28
+ - ⏰ **时间工具** - 常用的时间戳处理工具
29
+ - 📊 **统一响应格式** - 标准化的 API 响应结构
30
+ - 🛠 **基础工具类** - 提供 API 基类和通用功能
31
+ - 🧪 **完整测试** - 包含单元测试确保代码质量
32
+
33
+ ## 安装
34
+
35
+ ### 从 PyPI 安装
36
+
37
+ ```bash
38
+ pip install pytbox
39
+ ```
40
+
41
+ ### 从源码安装
42
+
43
+ ```bash
44
+ git clone https://github.com/your-username/pytbox.git
45
+ cd pytbox
46
+ pip install -e .
47
+ ```
48
+
49
+ ## 快速开始
50
+
51
+ ### VictoriaMetrics 查询
52
+
53
+ ```python
54
+ from pytbox.victoriametrics import VictoriaMetrics
55
+
56
+ # 初始化 VictoriaMetrics 客户端
57
+ vm = VictoriaMetrics(url="http://localhost:8428", timeout=5)
58
+
59
+ # 查询指标数据
60
+ result = vm.query('ping_average_response_ms')
61
+
62
+ if result.is_success():
63
+ print("查询成功:", result.data)
64
+ else:
65
+ print("查询失败:", result.msg)
66
+ ```
67
+
68
+ ### 时间工具使用
69
+
70
+ ```python
71
+ from pytbox.utils.timeutils import TimeUtils
72
+
73
+ # 获取当前时间戳(秒)
74
+ timestamp = TimeUtils.get_timestamp()
75
+ print(f"当前时间戳: {timestamp}")
76
+
77
+ # 获取当前时间戳(毫秒)
78
+ timestamp_ms = TimeUtils.get_timestamp(now=False)
79
+ print(f"当前时间戳(毫秒): {timestamp_ms}")
80
+ ```
81
+
82
+ ### 使用基础 API 类
83
+
84
+ ```python
85
+ from pytbox.common.base import BaseAPI
86
+
87
+ class MyAPI(BaseAPI):
88
+ def __init__(self):
89
+ super().__init__(base_url="https://api.example.com")
90
+
91
+ def make_request(self):
92
+ # 记录请求日志
93
+ log = self.log_request("GET", "/users", {"param": "value"})
94
+ print("请求日志:", log)
95
+
96
+ # 检查会话存活时间
97
+ age = self.get_session_age()
98
+ print(f"会话存活时间: {age} 秒")
99
+
100
+ api = MyAPI()
101
+ api.make_request()
102
+ ```
103
+
104
+ ### 统一响应格式
105
+
106
+ ```python
107
+ from pytbox.utils.response import ReturnResponse
108
+
109
+ # 创建成功响应
110
+ success_response = ReturnResponse(
111
+ code=0,
112
+ msg="操作成功",
113
+ data={"user_id": 123, "username": "admin"}
114
+ )
115
+
116
+ # 创建错误响应
117
+ error_response = ReturnResponse(
118
+ code=1,
119
+ msg="用户未找到",
120
+ data=None
121
+ )
122
+
123
+ # 检查响应状态
124
+ if success_response.is_success():
125
+ print("操作成功:", success_response.data)
126
+
127
+ if error_response.is_error():
128
+ print("操作失败:", error_response.msg)
129
+ ```
130
+
131
+ ## API 文档
132
+
133
+ ### VictoriaMetrics
134
+
135
+ #### `VictoriaMetrics(url, timeout=3)`
136
+
137
+ VictoriaMetrics 时序数据库客户端。
138
+
139
+ **参数:**
140
+ - `url` (str): VictoriaMetrics 服务器地址
141
+ - `timeout` (int): 请求超时时间,默认 3 秒
142
+
143
+ **方法:**
144
+
145
+ ##### `query(query: str) -> ReturnResponse`
146
+
147
+ 执行 PromQL 查询。
148
+
149
+ **参数:**
150
+ - `query` (str): PromQL 查询语句
151
+
152
+ **返回:**
153
+ - `ReturnResponse`: 统一响应格式,包含查询结果
154
+
155
+ ### TimeUtils
156
+
157
+ #### `TimeUtils.get_timestamp(now=True) -> int`
158
+
159
+ 获取时间戳。
160
+
161
+ **参数:**
162
+ - `now` (bool): True 返回秒级时间戳,False 返回毫秒级时间戳
163
+
164
+ **返回:**
165
+ - `int`: 时间戳
166
+
167
+ ### ReturnResponse
168
+
169
+ 统一的响应格式类,包含以下状态码:
170
+
171
+ - `0` - 成功 (SUCCESS)
172
+ - `1` - 一般错误 (ERROR)
173
+ - `2` - 警告 (WARNING)
174
+ - `3` - 未授权 (UNAUTHORIZED)
175
+ - `4` - 资源未找到 (NOT_FOUND)
176
+ - `5` - 请求超时 (TIMEOUT)
177
+ - `6` - 参数错误 (INVALID_PARAMS)
178
+ - `7` - 权限不足 (PERMISSION_DENIED)
179
+ - `8` - 服务不可用 (SERVICE_UNAVAILABLE)
180
+ - `9` - 数据库错误 (DATABASE_ERROR)
181
+ - `10` - 网络错误 (NETWORK_ERROR)
182
+
183
+ **方法:**
184
+ - `is_success() -> bool`: 判断是否为成功响应
185
+ - `is_error() -> bool`: 判断是否为错误响应
186
+
187
+ ## 开发
188
+
189
+ ### 安装开发依赖
190
+
191
+ ```bash
192
+ pip install -e ".[dev]"
193
+ ```
194
+
195
+ ### 运行测试
196
+
197
+ ```bash
198
+ pytest tests/
199
+ ```
200
+
201
+ ### 代码格式化
202
+
203
+ ```bash
204
+ black src/ tests/
205
+ ```
206
+
207
+ ### 代码检查
208
+
209
+ ```bash
210
+ ruff check src/ tests/
211
+ ```
212
+
213
+ ## 环境变量
214
+
215
+ 可以通过以下环境变量进行配置:
216
+
217
+ - `VICTORIAMETRICS_URL`: VictoriaMetrics 服务器地址(默认: http://localhost:8428)
218
+
219
+ ## 发布流程
220
+
221
+ 项目使用 GitHub Actions 自动发布到 PyPI:
222
+
223
+ 1. 更新版本号(在 `pyproject.toml` 中)
224
+ 2. 使用发布脚本创建标签:
225
+ ```bash
226
+ ./publish.sh 0.1.1
227
+ ```
228
+ 3. GitHub Actions 会自动构建并发布到 PyPI
229
+
230
+ ## 贡献
231
+
232
+ 欢迎提交 Issue 和 Pull Request!
233
+
234
+ 1. Fork 项目
235
+ 2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
236
+ 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
237
+ 4. 推送到分支 (`git push origin feature/AmazingFeature`)
238
+ 5. 开启 Pull Request
239
+
240
+ ## 许可证
241
+
242
+ 本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。
243
+
244
+ ## 更新日志
245
+
246
+ ### v0.1.0
247
+ - 初始版本发布
248
+ - 添加 VictoriaMetrics 集成
249
+ - 添加时间工具类
250
+ - 添加统一响应格式
251
+ - 添加基础 API 工具类
252
+
253
+ ## 联系方式
254
+
255
+ 如有问题或建议,请通过以下方式联系:
256
+
257
+ - 提交 [Issue](https://github.com/your-username/pytbox/issues)
258
+ - 发送邮件至 you@example.com
259
+
260
+ ---
261
+
262
+ **PytBox** - 让运维开发更简单! 🚀
@@ -0,0 +1,11 @@
1
+ pytbox/dida365.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ pytbox/timeutils.py,sha256=Nqnn8clbgv-5l0PgxcTOldg8mkMKrFn4TvPL-rYUUGg,1
3
+ pytbox/victoriametrics.py,sha256=xYizUXeazVQM7-MT9wxhqtfol2fZrXjfrt1qRgDsTKU,1098
4
+ pytbox/common/__init__.py,sha256=3JWfgCQZKZuSH5NCE7OCzKwq82pkyop9l7sH5YSNyfU,122
5
+ pytbox/common/base.py,sha256=aMKLcBi0-3UEYxANolE_qInC-0ZeydMGBB803xWzorI,1291
6
+ pytbox/utils/response.py,sha256=WAsA84VDyOTEaFl2jyGFNhAiYuoI-UHngb89AiUXD_U,1251
7
+ pytbox/utils/timeutils.py,sha256=ebTowUmWPnv1i1YfOqJo8s1mti1gA7qonJ-qnv5S-ZE,423
8
+ pytbox-20250818.2.dist-info/METADATA,sha256=3K7W__SsA8kgnFQVRuUPDVAq_biIuV_QikJVCb8y2sI,5926
9
+ pytbox-20250818.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ pytbox-20250818.2.dist-info/top_level.txt,sha256=YADgWue-Oe128ptN3J2hS3GB0Ncc5uZaSUM3e1rwswE,7
11
+ pytbox-20250818.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ pytbox