pytbox 0.0.1__tar.gz

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.
pytbox-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,264 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytbox
3
+ Version: 0.0.1
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
+ Requires-Dist: onepassword>=1.0.0
12
+ Requires-Dist: onepasswordconnectsdk>=1.0.0
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest; extra == "dev"
15
+ Requires-Dist: black; extra == "dev"
16
+ Requires-Dist: ruff; extra == "dev"
17
+ Requires-Dist: python-dotenv; extra == "dev"
18
+
19
+ # PytBox
20
+
21
+ [![PyPI version](https://img.shields.io/pypi/v/pytbox.svg)](https://pypi.org/project/pytbox/)
22
+ [![Python version](https://img.shields.io/pypi/pyversions/pytbox.svg)](https://pypi.org/project/pytbox/)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
24
+
25
+ 一个集成了多种服务和实用工具的 Python 包,专为运维开发场景设计。包含 VictoriaMetrics、滴答清单(Dida365)、飞书等服务的集成工具,以及常用的时间处理等实用工具。
26
+
27
+ ## 特性
28
+
29
+ - 🔍 **VictoriaMetrics 集成** - 提供时序数据库查询功能
30
+ - ⏰ **时间工具** - 常用的时间戳处理工具
31
+ - 📊 **统一响应格式** - 标准化的 API 响应结构
32
+ - 🛠 **基础工具类** - 提供 API 基类和通用功能
33
+ - 🧪 **完整测试** - 包含单元测试确保代码质量
34
+
35
+ ## 安装
36
+
37
+ ### 从 PyPI 安装
38
+
39
+ ```bash
40
+ pip install pytbox
41
+ ```
42
+
43
+ ### 从源码安装
44
+
45
+ ```bash
46
+ git clone https://github.com/your-username/pytbox.git
47
+ cd pytbox
48
+ pip install -e .
49
+ ```
50
+
51
+ ## 快速开始
52
+
53
+ ### VictoriaMetrics 查询
54
+
55
+ ```python
56
+ from pytbox.victoriametrics import VictoriaMetrics
57
+
58
+ # 初始化 VictoriaMetrics 客户端
59
+ vm = VictoriaMetrics(url="http://localhost:8428", timeout=5)
60
+
61
+ # 查询指标数据
62
+ result = vm.query('ping_average_response_ms')
63
+
64
+ if result.is_success():
65
+ print("查询成功:", result.data)
66
+ else:
67
+ print("查询失败:", result.msg)
68
+ ```
69
+
70
+ ### 时间工具使用
71
+
72
+ ```python
73
+ from pytbox.utils.timeutils import TimeUtils
74
+
75
+ # 获取当前时间戳(秒)
76
+ timestamp = TimeUtils.get_timestamp()
77
+ print(f"当前时间戳: {timestamp}")
78
+
79
+ # 获取当前时间戳(毫秒)
80
+ timestamp_ms = TimeUtils.get_timestamp(now=False)
81
+ print(f"当前时间戳(毫秒): {timestamp_ms}")
82
+ ```
83
+
84
+ ### 使用基础 API 类
85
+
86
+ ```python
87
+ from pytbox.common.base import BaseAPI
88
+
89
+ class MyAPI(BaseAPI):
90
+ def __init__(self):
91
+ super().__init__(base_url="https://api.example.com")
92
+
93
+ def make_request(self):
94
+ # 记录请求日志
95
+ log = self.log_request("GET", "/users", {"param": "value"})
96
+ print("请求日志:", log)
97
+
98
+ # 检查会话存活时间
99
+ age = self.get_session_age()
100
+ print(f"会话存活时间: {age} 秒")
101
+
102
+ api = MyAPI()
103
+ api.make_request()
104
+ ```
105
+
106
+ ### 统一响应格式
107
+
108
+ ```python
109
+ from pytbox.utils.response import ReturnResponse
110
+
111
+ # 创建成功响应
112
+ success_response = ReturnResponse(
113
+ code=0,
114
+ msg="操作成功",
115
+ data={"user_id": 123, "username": "admin"}
116
+ )
117
+
118
+ # 创建错误响应
119
+ error_response = ReturnResponse(
120
+ code=1,
121
+ msg="用户未找到",
122
+ data=None
123
+ )
124
+
125
+ # 检查响应状态
126
+ if success_response.is_success():
127
+ print("操作成功:", success_response.data)
128
+
129
+ if error_response.is_error():
130
+ print("操作失败:", error_response.msg)
131
+ ```
132
+
133
+ ## API 文档
134
+
135
+ ### VictoriaMetrics
136
+
137
+ #### `VictoriaMetrics(url, timeout=3)`
138
+
139
+ VictoriaMetrics 时序数据库客户端。
140
+
141
+ **参数:**
142
+ - `url` (str): VictoriaMetrics 服务器地址
143
+ - `timeout` (int): 请求超时时间,默认 3 秒
144
+
145
+ **方法:**
146
+
147
+ ##### `query(query: str) -> ReturnResponse`
148
+
149
+ 执行 PromQL 查询。
150
+
151
+ **参数:**
152
+ - `query` (str): PromQL 查询语句
153
+
154
+ **返回:**
155
+ - `ReturnResponse`: 统一响应格式,包含查询结果
156
+
157
+ ### TimeUtils
158
+
159
+ #### `TimeUtils.get_timestamp(now=True) -> int`
160
+
161
+ 获取时间戳。
162
+
163
+ **参数:**
164
+ - `now` (bool): True 返回秒级时间戳,False 返回毫秒级时间戳
165
+
166
+ **返回:**
167
+ - `int`: 时间戳
168
+
169
+ ### ReturnResponse
170
+
171
+ 统一的响应格式类,包含以下状态码:
172
+
173
+ - `0` - 成功 (SUCCESS)
174
+ - `1` - 一般错误 (ERROR)
175
+ - `2` - 警告 (WARNING)
176
+ - `3` - 未授权 (UNAUTHORIZED)
177
+ - `4` - 资源未找到 (NOT_FOUND)
178
+ - `5` - 请求超时 (TIMEOUT)
179
+ - `6` - 参数错误 (INVALID_PARAMS)
180
+ - `7` - 权限不足 (PERMISSION_DENIED)
181
+ - `8` - 服务不可用 (SERVICE_UNAVAILABLE)
182
+ - `9` - 数据库错误 (DATABASE_ERROR)
183
+ - `10` - 网络错误 (NETWORK_ERROR)
184
+
185
+ **方法:**
186
+ - `is_success() -> bool`: 判断是否为成功响应
187
+ - `is_error() -> bool`: 判断是否为错误响应
188
+
189
+ ## 开发
190
+
191
+ ### 安装开发依赖
192
+
193
+ ```bash
194
+ pip install -e ".[dev]"
195
+ ```
196
+
197
+ ### 运行测试
198
+
199
+ ```bash
200
+ pytest tests/
201
+ ```
202
+
203
+ ### 代码格式化
204
+
205
+ ```bash
206
+ black src/ tests/
207
+ ```
208
+
209
+ ### 代码检查
210
+
211
+ ```bash
212
+ ruff check src/ tests/
213
+ ```
214
+
215
+ ## 环境变量
216
+
217
+ 可以通过以下环境变量进行配置:
218
+
219
+ - `VICTORIAMETRICS_URL`: VictoriaMetrics 服务器地址(默认: http://localhost:8428)
220
+
221
+ ## 发布流程
222
+
223
+ 项目使用 GitHub Actions 自动发布到 PyPI:
224
+
225
+ 1. 更新版本号(在 `pyproject.toml` 中)
226
+ 2. 使用发布脚本创建标签:
227
+ ```bash
228
+ ./publish.sh 0.1.1
229
+ ```
230
+ 3. GitHub Actions 会自动构建并发布到 PyPI
231
+
232
+ ## 贡献
233
+
234
+ 欢迎提交 Issue 和 Pull Request!
235
+
236
+ 1. Fork 项目
237
+ 2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
238
+ 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
239
+ 4. 推送到分支 (`git push origin feature/AmazingFeature`)
240
+ 5. 开启 Pull Request
241
+
242
+ ## 许可证
243
+
244
+ 本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。
245
+
246
+ ## 更新日志
247
+
248
+ ### v0.1.0
249
+ - 初始版本发布
250
+ - 添加 VictoriaMetrics 集成
251
+ - 添加时间工具类
252
+ - 添加统一响应格式
253
+ - 添加基础 API 工具类
254
+
255
+ ## 联系方式
256
+
257
+ 如有问题或建议,请通过以下方式联系:
258
+
259
+ - 提交 [Issue](https://github.com/your-username/pytbox/issues)
260
+ - 发送邮件至 houm01@foxmail.com
261
+
262
+ ---
263
+
264
+ **PytBox** - 让运维开发更简单! 🚀
pytbox-0.0.1/README.md ADDED
@@ -0,0 +1,246 @@
1
+ # PytBox
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/pytbox.svg)](https://pypi.org/project/pytbox/)
4
+ [![Python version](https://img.shields.io/pypi/pyversions/pytbox.svg)](https://pypi.org/project/pytbox/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ 一个集成了多种服务和实用工具的 Python 包,专为运维开发场景设计。包含 VictoriaMetrics、滴答清单(Dida365)、飞书等服务的集成工具,以及常用的时间处理等实用工具。
8
+
9
+ ## 特性
10
+
11
+ - 🔍 **VictoriaMetrics 集成** - 提供时序数据库查询功能
12
+ - ⏰ **时间工具** - 常用的时间戳处理工具
13
+ - 📊 **统一响应格式** - 标准化的 API 响应结构
14
+ - 🛠 **基础工具类** - 提供 API 基类和通用功能
15
+ - 🧪 **完整测试** - 包含单元测试确保代码质量
16
+
17
+ ## 安装
18
+
19
+ ### 从 PyPI 安装
20
+
21
+ ```bash
22
+ pip install pytbox
23
+ ```
24
+
25
+ ### 从源码安装
26
+
27
+ ```bash
28
+ git clone https://github.com/your-username/pytbox.git
29
+ cd pytbox
30
+ pip install -e .
31
+ ```
32
+
33
+ ## 快速开始
34
+
35
+ ### VictoriaMetrics 查询
36
+
37
+ ```python
38
+ from pytbox.victoriametrics import VictoriaMetrics
39
+
40
+ # 初始化 VictoriaMetrics 客户端
41
+ vm = VictoriaMetrics(url="http://localhost:8428", timeout=5)
42
+
43
+ # 查询指标数据
44
+ result = vm.query('ping_average_response_ms')
45
+
46
+ if result.is_success():
47
+ print("查询成功:", result.data)
48
+ else:
49
+ print("查询失败:", result.msg)
50
+ ```
51
+
52
+ ### 时间工具使用
53
+
54
+ ```python
55
+ from pytbox.utils.timeutils import TimeUtils
56
+
57
+ # 获取当前时间戳(秒)
58
+ timestamp = TimeUtils.get_timestamp()
59
+ print(f"当前时间戳: {timestamp}")
60
+
61
+ # 获取当前时间戳(毫秒)
62
+ timestamp_ms = TimeUtils.get_timestamp(now=False)
63
+ print(f"当前时间戳(毫秒): {timestamp_ms}")
64
+ ```
65
+
66
+ ### 使用基础 API 类
67
+
68
+ ```python
69
+ from pytbox.common.base import BaseAPI
70
+
71
+ class MyAPI(BaseAPI):
72
+ def __init__(self):
73
+ super().__init__(base_url="https://api.example.com")
74
+
75
+ def make_request(self):
76
+ # 记录请求日志
77
+ log = self.log_request("GET", "/users", {"param": "value"})
78
+ print("请求日志:", log)
79
+
80
+ # 检查会话存活时间
81
+ age = self.get_session_age()
82
+ print(f"会话存活时间: {age} 秒")
83
+
84
+ api = MyAPI()
85
+ api.make_request()
86
+ ```
87
+
88
+ ### 统一响应格式
89
+
90
+ ```python
91
+ from pytbox.utils.response import ReturnResponse
92
+
93
+ # 创建成功响应
94
+ success_response = ReturnResponse(
95
+ code=0,
96
+ msg="操作成功",
97
+ data={"user_id": 123, "username": "admin"}
98
+ )
99
+
100
+ # 创建错误响应
101
+ error_response = ReturnResponse(
102
+ code=1,
103
+ msg="用户未找到",
104
+ data=None
105
+ )
106
+
107
+ # 检查响应状态
108
+ if success_response.is_success():
109
+ print("操作成功:", success_response.data)
110
+
111
+ if error_response.is_error():
112
+ print("操作失败:", error_response.msg)
113
+ ```
114
+
115
+ ## API 文档
116
+
117
+ ### VictoriaMetrics
118
+
119
+ #### `VictoriaMetrics(url, timeout=3)`
120
+
121
+ VictoriaMetrics 时序数据库客户端。
122
+
123
+ **参数:**
124
+ - `url` (str): VictoriaMetrics 服务器地址
125
+ - `timeout` (int): 请求超时时间,默认 3 秒
126
+
127
+ **方法:**
128
+
129
+ ##### `query(query: str) -> ReturnResponse`
130
+
131
+ 执行 PromQL 查询。
132
+
133
+ **参数:**
134
+ - `query` (str): PromQL 查询语句
135
+
136
+ **返回:**
137
+ - `ReturnResponse`: 统一响应格式,包含查询结果
138
+
139
+ ### TimeUtils
140
+
141
+ #### `TimeUtils.get_timestamp(now=True) -> int`
142
+
143
+ 获取时间戳。
144
+
145
+ **参数:**
146
+ - `now` (bool): True 返回秒级时间戳,False 返回毫秒级时间戳
147
+
148
+ **返回:**
149
+ - `int`: 时间戳
150
+
151
+ ### ReturnResponse
152
+
153
+ 统一的响应格式类,包含以下状态码:
154
+
155
+ - `0` - 成功 (SUCCESS)
156
+ - `1` - 一般错误 (ERROR)
157
+ - `2` - 警告 (WARNING)
158
+ - `3` - 未授权 (UNAUTHORIZED)
159
+ - `4` - 资源未找到 (NOT_FOUND)
160
+ - `5` - 请求超时 (TIMEOUT)
161
+ - `6` - 参数错误 (INVALID_PARAMS)
162
+ - `7` - 权限不足 (PERMISSION_DENIED)
163
+ - `8` - 服务不可用 (SERVICE_UNAVAILABLE)
164
+ - `9` - 数据库错误 (DATABASE_ERROR)
165
+ - `10` - 网络错误 (NETWORK_ERROR)
166
+
167
+ **方法:**
168
+ - `is_success() -> bool`: 判断是否为成功响应
169
+ - `is_error() -> bool`: 判断是否为错误响应
170
+
171
+ ## 开发
172
+
173
+ ### 安装开发依赖
174
+
175
+ ```bash
176
+ pip install -e ".[dev]"
177
+ ```
178
+
179
+ ### 运行测试
180
+
181
+ ```bash
182
+ pytest tests/
183
+ ```
184
+
185
+ ### 代码格式化
186
+
187
+ ```bash
188
+ black src/ tests/
189
+ ```
190
+
191
+ ### 代码检查
192
+
193
+ ```bash
194
+ ruff check src/ tests/
195
+ ```
196
+
197
+ ## 环境变量
198
+
199
+ 可以通过以下环境变量进行配置:
200
+
201
+ - `VICTORIAMETRICS_URL`: VictoriaMetrics 服务器地址(默认: http://localhost:8428)
202
+
203
+ ## 发布流程
204
+
205
+ 项目使用 GitHub Actions 自动发布到 PyPI:
206
+
207
+ 1. 更新版本号(在 `pyproject.toml` 中)
208
+ 2. 使用发布脚本创建标签:
209
+ ```bash
210
+ ./publish.sh 0.1.1
211
+ ```
212
+ 3. GitHub Actions 会自动构建并发布到 PyPI
213
+
214
+ ## 贡献
215
+
216
+ 欢迎提交 Issue 和 Pull Request!
217
+
218
+ 1. Fork 项目
219
+ 2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
220
+ 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
221
+ 4. 推送到分支 (`git push origin feature/AmazingFeature`)
222
+ 5. 开启 Pull Request
223
+
224
+ ## 许可证
225
+
226
+ 本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。
227
+
228
+ ## 更新日志
229
+
230
+ ### v0.1.0
231
+ - 初始版本发布
232
+ - 添加 VictoriaMetrics 集成
233
+ - 添加时间工具类
234
+ - 添加统一响应格式
235
+ - 添加基础 API 工具类
236
+
237
+ ## 联系方式
238
+
239
+ 如有问题或建议,请通过以下方式联系:
240
+
241
+ - 提交 [Issue](https://github.com/your-username/pytbox/issues)
242
+ - 发送邮件至 houm01@foxmail.com
243
+
244
+ ---
245
+
246
+ **PytBox** - 让运维开发更简单! 🚀
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pytbox"
7
+ version = "0.0.1"
8
+ description = "A collection of Python integrations and utilities (Feishu, Dida365, VictoriaMetrics, ...)"
9
+ authors = [{ name = "mingming hou", email = "houm01@foxmail.com" }]
10
+ license = { text = "MIT" }
11
+ readme = "README.md"
12
+ requires-python = ">=3.8"
13
+
14
+ dependencies = [
15
+ "requests>=2.0",
16
+ "pydantic>=1.10",
17
+ "onepassword>=1.0.0",
18
+ "onepasswordconnectsdk>=1.0.0",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["pytest", "black", "ruff", "python-dotenv"]
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
pytbox-0.0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env python3
2
+
3
+ from typing import Literal
4
+ # 引入sls包。
5
+ from aliyun.log import GetLogsRequest, LogItem, PutLogsRequest
6
+ from aliyun.log import LogClient as SlsLogClient
7
+ from aliyun.log.auth import AUTH_VERSION_4
8
+ from ..utils.env import check_env
9
+
10
+
11
+
12
+ class AliCloudSls:
13
+
14
+ def __init__(self, access_key_id: str=None, access_key_secret: str=None, project: str, logstore: str):
15
+ # 日志服务的服务接入点
16
+ self.endpoint = "cn-shanghai.log.aliyuncs.com"
17
+ # 创建 LogClient 实例,使用 V4 签名,根据实际情况填写 region,这里以杭州为例
18
+ self.client = SlsLogClient(self.endpoint, access_key_id, access_key_secret, auth_version=AUTH_VERSION_4, region='cn-shanghai')
19
+ self.project = project
20
+ self.logstore = logstore
21
+
22
+ def get_logs(self, project_name, logstore_name, query, from_time, to_time):
23
+ # Project名称。
24
+ # project_name = "sh-prod-network-devices-log"
25
+ # Logstore名称
26
+ # logstore_name = "sh-prod-network-devices-log"
27
+ # 查询语句。
28
+ # query = "*| select dev,id from " + logstore_name
29
+ # query = "*"
30
+ # 索引。
31
+ logstore_index = {'line': {
32
+ 'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t',
33
+ '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'dev': {'type': 'text',
34
+ 'token': [',', ' ', "'", '"', ';', '=',
35
+ '(', ')', '[', ']', '{', '}',
36
+ '?', '@', '&', '<', '>', '/',
37
+ ':', '\n', '\t', '\r'],
38
+ 'caseSensitive': False, 'alias': '',
39
+ 'doc_value': True, 'chn': False},
40
+ 'id': {'type': 'long', 'alias': '',
41
+ 'doc_value': True}}, 'log_reduce': False,
42
+ 'max_text_len': 2048}
43
+
44
+ # from_time和to_time表示查询日志的时间范围,Unix时间戳格式。
45
+ # from_time = int(time.time()) - 60
46
+ # to_time = time.time() + 60
47
+ # # 通过SQL查询日志。
48
+ # def get_logs():
49
+ # print("ready to query logs from logstore %s" % logstore_name)
50
+ request = GetLogsRequest(project_name, logstore_name, from_time, to_time, query=query)
51
+ response = self.client.get_logs(request)
52
+ for log in response.get_logs():
53
+ yield log.contents
54
+
55
+ def put_logs(self,
56
+ topic: Literal['meraki_alert', 'program']='program',
57
+ level: Literal['INFO', 'WARN']='INFO',
58
+ msg: str=None,
59
+ app: str=None,
60
+ caller_filename: str=None,
61
+ caller_lineno: int=None,
62
+ caller_function: str=None,
63
+ call_full_filename: str=None
64
+ ):
65
+ log_group = []
66
+ log_item = LogItem()
67
+ contents = [
68
+ ('env', check_env()),
69
+ ('level', level),
70
+ ('app', app),
71
+ ('msg', msg),
72
+ ('caller_filename', caller_filename),
73
+ ('caller_lineno', str(caller_lineno)),
74
+ ('caller_function', caller_function),
75
+ ('call_full_filename', call_full_filename)
76
+ ]
77
+ log_item.set_contents(contents)
78
+ log_group.append(log_item)
79
+ request = PutLogsRequest(self.project, self.logstore, topic, "", log_group, compress=False)
80
+ self.client.put_logs(request)
81
+
82
+ def put_logs_for_meraki(self, alert):
83
+ log_group = []
84
+ log_item = LogItem()
85
+ contents = alert
86
+ log_item.set_contents(contents)
87
+ log_group.append(log_item)
88
+ request = PutLogsRequest(self.project, self.logstore, "", "", log_group, compress=False)
89
+ self.client.put_logs(request)
90
+
91
+
92
+ if __name__ == "__main__":
93
+ pass
@@ -0,0 +1,7 @@
1
+ """
2
+ Common utilities and base classes
3
+ """
4
+
5
+ from .base import BaseAPI, BaseResponse
6
+
7
+ __all__ = ["BaseAPI", "BaseResponse"]
File without changes