pytbox 0.0.1__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.

pytbox/victorialog.py ADDED
@@ -0,0 +1,125 @@
1
+
2
+
3
+ from typing import Literal
4
+ import requests
5
+ import time
6
+ from .utils.response import ReturnResponse
7
+ from .utils.timeutils import TimeUtils
8
+
9
+
10
+
11
+ class Victorialog:
12
+ '''
13
+ _summary_
14
+ '''
15
+ def __init__(self, url: str=None, timeout: int=3):
16
+ self.url = url
17
+ self.timeout = timeout
18
+
19
+ def send_program_log(self,
20
+ stream: str='inbox',
21
+ date: str = None,
22
+ level: Literal['INFO', 'DEBUG', 'WARNING', 'ERROR', 'CRITICAL', 'SUCCESS'] = 'INFO',
23
+ message: str = "test",
24
+ app_name: str = "test",
25
+ file_name: str = None,
26
+ line_number: int = None,
27
+ function_name: str = None
28
+ ) -> ReturnResponse:
29
+
30
+ # 如果没有提供timestamp,自动生成ISO 8601格式的UTC时间
31
+ if date is None:
32
+ date = TimeUtils.get_utc_time()
33
+
34
+ if not isinstance(message, str):
35
+ try:
36
+ message = str(message)
37
+ except Exception:
38
+ message = "message 无法转换为字符串"
39
+
40
+ r = requests.post(
41
+ url=self.url + '/insert/jsonline?_stream_fields=stream&_time_field=date&_msg_field=log.message',
42
+ headers={'Content-Type': 'application/stream+json'},
43
+ json={
44
+ "log": {
45
+ "level": level,
46
+ "message": message,
47
+ "app": app_name,
48
+ "file": file_name,
49
+ "line": line_number,
50
+ "function": function_name
51
+ },
52
+ "date": date,
53
+ "stream": stream
54
+ },
55
+ timeout=self.timeout
56
+ )
57
+ if r.status_code == 200:
58
+ return ReturnResponse(code=0, msg=f"{message} 发送成功", data=r.text)
59
+ else:
60
+ return ReturnResponse(code=1, msg=f"{message} 发送失败")
61
+
62
+ def send_syslog(self, stream, hostname, ip, level, message, date):
63
+
64
+ # 如果没有提供timestamp,自动生成ISO 8601格式的UTC时间
65
+ if date is None:
66
+ date = TimeUtils.get_utc_time()
67
+
68
+ r = requests.post(
69
+ url=self.url,
70
+ headers={'Content-Type': 'application/stream+json'},
71
+ json={
72
+ "log": {
73
+ "hostname": hostname,
74
+ "ip": ip,
75
+ "level": level,
76
+ "message": message,
77
+ },
78
+ "date": date,
79
+ "stream": stream
80
+ },
81
+ timeout=self.timeout
82
+ )
83
+ if r.status_code == 200:
84
+ return ReturnResponse(code=0, msg=f"{message} 发送成功", data=r.text)
85
+ else:
86
+ return ReturnResponse(code=1, msg=f"{message} 发送失败")
87
+
88
+ def query(self, query: str=None, delay: int=0) -> ReturnResponse:
89
+ """
90
+ 查询日志数据
91
+
92
+ Args:
93
+ query: 查询语句
94
+ limit: 限制返回结果数量
95
+ **kwargs: 其他表单参数,如 start_time, end_time 等
96
+
97
+ Returns:
98
+ dict: 响应数据
99
+ """
100
+
101
+ # 构建查询URL
102
+ query_url = f"{self.url}/select/logsql/query"
103
+
104
+ # 构建表单数据
105
+ form_data = {'query': query}
106
+ if delay > 0:
107
+ time.sleep(delay)
108
+ # 发送POST请求,data参数传递多个表单数据
109
+ response = requests.post(
110
+ url=query_url,
111
+ # headers={'Content-Type': 'application/stream+json'},
112
+ data=form_data, # 使用data参数传递多个表单数据
113
+ timeout=self.timeout
114
+ )
115
+ if response.status_code == 200:
116
+ if len(response.text) > 0:
117
+ return ReturnResponse(code=0, message=f"{form_data} 查询成功", data=response.text)
118
+ else:
119
+ return ReturnResponse(code=2, message=f"{form_data} 查询成功, 但没有数据")
120
+ else:
121
+ return ReturnResponse(code=1, message=f"{form_data} 查询失败")
122
+
123
+ if __name__ == "__main__":
124
+ victorialog = Victorialog()
125
+ pass
@@ -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,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** - 让运维开发更简单! 🚀
@@ -0,0 +1,21 @@
1
+ pytbox/dida365.py,sha256=s6ipeweXMV3CaatFFwuxEwBLGK9jJ0B6GP7dQMYxpDo,10592
2
+ pytbox/logger.py,sha256=4IHmMg14Rwekmc7AeKGDbsDZryhcD6elaJZsvpdYJ80,5659
3
+ pytbox/onepassword_connect.py,sha256=nD3xTl1ykQ4ct_dCRRF138gXCtk-phPfKYXuOn-P7Z8,3064
4
+ pytbox/onepassword_sa.py,sha256=08iUcYud3aEHuQcUsem9bWNxdXKgaxFbMy9yvtr-DZQ,6995
5
+ pytbox/victorialog.py,sha256=50cVPxq9PzzzkzQHhgv_785K3GeF8B2mEnChdeekZWU,4137
6
+ pytbox/victoriametrics.py,sha256=xYizUXeazVQM7-MT9wxhqtfol2fZrXjfrt1qRgDsTKU,1098
7
+ pytbox/alicloud/sls.py,sha256=WZuxt6NjY3Sf9KMF4DoDlCoxbdqGL2lyymp6jQW-wJc,4355
8
+ pytbox/common/__init__.py,sha256=3JWfgCQZKZuSH5NCE7OCzKwq82pkyop9l7sH5YSNyfU,122
9
+ pytbox/common/base.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ pytbox/feishu/client.py,sha256=kwGLseGT_iQUFmSqpuS2_77WmxtHstD64nXvktuQ3B4,5865
11
+ pytbox/feishu/endpoints.py,sha256=z_nHGXAjlIyYdFnbAWY4hfzzHrENJvoNOqY9sA6-FLk,40009
12
+ pytbox/feishu/errors.py,sha256=79qFAHZw7jDj3gnWAjI1-W4tB0q1_aSfdjee4xzXeuI,1179
13
+ pytbox/feishu/helpers.py,sha256=jhSkHiUw4822QBXx2Jw8AksogZdakZ-3QqvC3lB3qEI,201
14
+ pytbox/feishu/typing.py,sha256=3hWkJgOi-v2bt9viMxkyvNHsPgrbAa0aZOxsZYg2vdM,122
15
+ pytbox/utils/env.py,sha256=jO_-BKbGuDU7lIL9KYkcxGCzQwTXfxD4mIYtSAjREmI,622
16
+ pytbox/utils/response.py,sha256=WAsA84VDyOTEaFl2jyGFNhAiYuoI-UHngb89AiUXD_U,1251
17
+ pytbox/utils/timeutils.py,sha256=zMf6Oe7dc5oR-yyvMxznq8Jr78S_WRVmhg-Z7hJdypQ,979
18
+ pytbox-0.0.1.dist-info/METADATA,sha256=aDRXMGyuwmnzJUjz1WGhGJU-VSXepcAnpvbrlWiZri0,6002
19
+ pytbox-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
20
+ pytbox-0.0.1.dist-info/top_level.txt,sha256=YADgWue-Oe128ptN3J2hS3GB0Ncc5uZaSUM3e1rwswE,7
21
+ pytbox-0.0.1.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