ezKit 2.0.37__tar.gz → 3.0.0__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.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ezKit
3
- Version: 2.0.37
3
+ Version: 3.0.0
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
7
- Requires-Python: >=3.12
7
+ Requires-Python: >=3.13
8
8
  License-File: LICENSE
9
9
  Requires-Dist: loguru>=0.7
10
10
  Dynamic: author
@@ -0,0 +1,86 @@
1
+ """Database Library"""
2
+
3
+ from contextlib import contextmanager
4
+ from os import environ
5
+
6
+ from loguru import logger
7
+ from sqlalchemy import TextClause, text
8
+ from sqlalchemy.engine import CursorResult, ScalarResult
9
+ from sqlalchemy.orm import sessionmaker
10
+ from sqlalchemy.sql import Delete, Insert, Select, Update
11
+
12
+ # --------------------------------------------------------------------------------------------------
13
+
14
+ DEBUG = environ.get("DEBUG")
15
+
16
+ # --------------------------------------------------------------------------------------------------
17
+
18
+ # 同步 (Sync) 数据库操作类
19
+
20
+
21
+ class Database:
22
+
23
+ def __init__(self, db_session: sessionmaker):
24
+
25
+ self._db_session: sessionmaker = db_session
26
+
27
+ @contextmanager
28
+ def _get_db(self):
29
+ """公用数据库连接上下文管理器"""
30
+ session = self._db_session()
31
+ try:
32
+ yield session # 将 session 传递给 with 语句
33
+ session.commit() # 如果没有报错,自动提交(可选,不需要自动提交可以删掉这行)
34
+ except Exception as e:
35
+ session.rollback() # 发生异常自动回滚
36
+ raise e
37
+ finally:
38
+ session.close()
39
+
40
+ def execute(self, statement: str | TextClause | Delete | Insert | Select | Update, scalars: bool = False) -> CursorResult | ScalarResult | None:
41
+ """database execute statement"""
42
+
43
+ # SQL 语句既可以是 text() 对象 也可以是 ORM 构建的 statement 对象
44
+ #
45
+ # text() 对象可以是任意 SQL 语句
46
+ # statement 对象包括 select, insert, update, delete 等
47
+
48
+ info: str = "database execute statement"
49
+
50
+ if DEBUG:
51
+ logger.debug(f"{info} | SQL\n----------\n\n{statement}\n\n----------")
52
+
53
+ logger.info(f"{info} | start")
54
+
55
+ try:
56
+ stmt = text(statement) if isinstance(statement, str) else statement
57
+ with self._get_db() as session:
58
+ result: CursorResult | ScalarResult = session.scalars(stmt) if scalars else session.execute(stmt)
59
+ logger.success(f"{info} | success")
60
+ return result
61
+ except Exception as e:
62
+ logger.error(f"{info} | error")
63
+ if DEBUG:
64
+ logger.exception(e)
65
+ else:
66
+ logger.error(e)
67
+ return None
68
+
69
+ # 连接测试
70
+ def connection_test(self) -> bool:
71
+ """database connection test"""
72
+
73
+ logger.info("database connection test | start")
74
+
75
+ try:
76
+ with self._get_db() as session:
77
+ session.execute(text("SELECT 1;"))
78
+ logger.success("database connection test | success")
79
+ return True
80
+ except Exception as e:
81
+ logger.error("database connection test | error")
82
+ if DEBUG:
83
+ logger.exception(e)
84
+ else:
85
+ logger.error(e)
86
+ return False
@@ -0,0 +1,51 @@
1
+ """Utils Library"""
2
+
3
+ from os import environ
4
+ from typing import Any
5
+
6
+ from loguru import logger
7
+
8
+ # --------------------------------------------------------------------------------------------------
9
+
10
+ DEBUG = environ.get("DEBUG")
11
+
12
+ # --------------------------------------------------------------------------------------------------
13
+
14
+
15
+ def isTrue(target: object, typeClass: Any) -> bool:
16
+ """检查对象是否为真"""
17
+
18
+ # 常见布尔类型:
19
+ #
20
+ # Boolean bool False
21
+ # Numbers int/float 0/0.0
22
+ # String str ""
23
+ # List list/tuple/set []/()/{}
24
+ # Dictionary dict {}
25
+ # Set set set()
26
+ #
27
+ # 查看变量类型: type(x)
28
+ #
29
+ # 判断变量类型: isinstance(x, str)
30
+ #
31
+ # 函数使用 callable(func) 判断
32
+ #
33
+ # 判断多个类型:
34
+ #
35
+ # isTrue("abc", (str, int))
36
+ # isTrue("abc", (str | int))
37
+ #
38
+ # all() 用于检查一个可迭代对象(如列表、元组、集合等)中的 所有 元素是否为 真值 (truthy), 所有元素为真, 返回 True
39
+ # any() 用于检查一个可迭代对象(如列表、元组、集合等)中的 某个 元素是否为 真值 (truthy), 某个元素为真, 返回 True
40
+ # 与 all() 作用相反的 not any(), 可以用来检查所有元素是否为 假值 (falsy), any() 中所有元素为假, not any() 返回 True
41
+ #
42
+ # return target not in [False, None, 0, 0.0, '', (), [], {}, set(), {*()}, {*[]}, {*{}}, {*set()}]
43
+
44
+ try:
45
+ return bool(isinstance(target, typeClass) and target)
46
+ except Exception as e:
47
+ if DEBUG:
48
+ logger.exception(e)
49
+ else:
50
+ logger.error(e)
51
+ return False
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ezKit
3
- Version: 2.0.37
3
+ Version: 3.0.0
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
7
- Requires-Python: >=3.12
7
+ Requires-Python: >=3.13
8
8
  License-File: LICENSE
9
9
  Requires-Dist: loguru>=0.7
10
10
  Dynamic: author
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ setup.py
6
+ ezKit/__init__.py
7
+ ezKit/database.py
8
+ ezKit/utils.py
9
+ ezKit.egg-info/PKG-INFO
10
+ ezKit.egg-info/SOURCES.txt
11
+ ezKit.egg-info/dependency_links.txt
12
+ ezKit.egg-info/requires.txt
13
+ ezKit.egg-info/top_level.txt
@@ -19,7 +19,7 @@
19
19
  # known_first_party = ["./source"]
20
20
 
21
21
  [tool.ruff]
22
- target-version = "py312"
22
+ target-version = "py313"
23
23
  line-length = 100
24
24
 
25
25
  [tool.ruff.lint]
@@ -4,13 +4,13 @@ from setuptools import find_packages, setup
4
4
 
5
5
  setup(
6
6
  name="ezKit",
7
- version="2.0.37",
7
+ version="3.0.0",
8
8
  author="septvean",
9
9
  author_email="septvean@gmail.com",
10
10
  description="Easy Kit",
11
- packages=find_packages(exclude=["deprecated", "documents", "tests"]),
11
+ packages=find_packages(exclude=["deprecated", "documents", "pending", "tests"]),
12
12
  include_package_data=True,
13
13
  package_data={"ezKit": ["markdown_to_html.template"]},
14
- python_requires=">=3.12",
14
+ python_requires=">=3.13",
15
15
  install_requires=["loguru>=0.7"],
16
16
  )
@@ -1,296 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- from operator import itemgetter
5
- from typing import Any
6
-
7
- import requests
8
- from loguru import logger
9
-
10
- # =============================================================================
11
- # Exceptions
12
- # =============================================================================
13
-
14
-
15
- class ZabbixError(RuntimeError):
16
- """Zabbix API error"""
17
-
18
-
19
- # =============================================================================
20
- # Utils
21
- # =============================================================================
22
-
23
-
24
- def sort_dicts(
25
- data: list[dict],
26
- key: str,
27
- *,
28
- reverse: bool = False,
29
- ) -> list[dict]:
30
- return sorted(data, key=itemgetter(key), reverse=reverse)
31
-
32
-
33
- # =============================================================================
34
- # Zabbix Client
35
- # =============================================================================
36
-
37
-
38
- class Zabbix:
39
- def __init__(self, api: str, username: str, password: str) -> None:
40
- self.api = api
41
- self.auth = self._login(username, password)
42
-
43
- # -------------------------------------------------------------------------
44
- # Core Request
45
- # -------------------------------------------------------------------------
46
-
47
- def request(self, method: str, params: dict | list) -> dict:
48
- if not self.api:
49
- raise ZabbixError("Zabbix API URL not set")
50
-
51
- payload = {
52
- "jsonrpc": "2.0",
53
- "method": method,
54
- "params": params,
55
- "auth": None if method == "apiinfo.version" else self.auth,
56
- "id": int(time.time()),
57
- }
58
-
59
- resp = requests.post(
60
- self.api,
61
- json=payload,
62
- headers={"Content-Type": "application/json-rpc"},
63
- timeout=10,
64
- )
65
-
66
- resp.raise_for_status()
67
- data = resp.json()
68
-
69
- if "error" in data:
70
- raise ZabbixError(data["error"])
71
-
72
- return data["result"]
73
-
74
- # -------------------------------------------------------------------------
75
- # Auth
76
- # -------------------------------------------------------------------------
77
-
78
- def _login(self, username: str, password: str) -> str:
79
- logger.info("Login started")
80
-
81
- result = self.request(
82
- "user.login",
83
- {"username": username, "password": password},
84
- )
85
-
86
- logger.success("Login succeeded")
87
- return result
88
-
89
- def logout(self) -> None:
90
- self.request("user.logout", {})
91
- logger.success("Logout succeeded")
92
-
93
- # -------------------------------------------------------------------------
94
- # Basic Info
95
- # -------------------------------------------------------------------------
96
-
97
- def get_version(self) -> dict:
98
- return self.request("apiinfo.version", {})
99
-
100
- # -------------------------------------------------------------------------
101
- # Host / Group / Template
102
- # -------------------------------------------------------------------------
103
-
104
- def get_hostgroup_ids(self, name: str) -> list[str]:
105
- result = self.request(
106
- "hostgroup.get",
107
- {"output": ["groupid"], "filter": {"name": name}},
108
- )
109
- return [r["groupid"] for r in result]
110
-
111
- def get_template_ids(self, name: str) -> list[str]:
112
- result = self.request(
113
- "template.get",
114
- {"output": ["templateid"], "filter": {"name": name}},
115
- )
116
- return [r["templateid"] for r in result]
117
-
118
- def get_hosts_by_group(self, name: str, output: str | list = "extend") -> list[dict]:
119
- group_ids = self.get_hostgroup_ids(name)
120
- return self.request(
121
- "host.get",
122
- {"output": output, "groupids": group_ids},
123
- )
124
-
125
- def get_hosts_by_template(self, name: str, output: str | list = "extend") -> list[dict]:
126
- template_ids = self.get_template_ids(name)
127
- return self.request(
128
- "host.get",
129
- {"output": output, "templateids": template_ids},
130
- )
131
-
132
- # -------------------------------------------------------------------------
133
- # Interface
134
- # -------------------------------------------------------------------------
135
-
136
- def get_interfaces(self, hostids: list[str]) -> list[dict]:
137
- return self.request(
138
- "hostinterface.get",
139
- {"hostids": hostids},
140
- )
141
-
142
- # -------------------------------------------------------------------------
143
- # History
144
- # -------------------------------------------------------------------------
145
-
146
- def _get_items_by_key(
147
- self,
148
- hostids: list[str],
149
- item_key: str,
150
- ) -> dict[str, str]:
151
- items = self.request(
152
- "item.get",
153
- {
154
- "output": ["itemid", "hostid"],
155
- "hostids": hostids,
156
- "filter": {"key_": item_key},
157
- },
158
- )
159
-
160
- return {item["hostid"]: item["itemid"] for item in items}
161
-
162
- def _get_history(
163
- self,
164
- itemids: list[str],
165
- time_from: int,
166
- time_till: int,
167
- data_type: int,
168
- ) -> list[dict]:
169
- return self.request(
170
- "history.get",
171
- {
172
- "output": "extend",
173
- "history": data_type,
174
- "itemids": itemids,
175
- "time_from": time_from,
176
- "time_till": time_till,
177
- },
178
- )
179
-
180
- def get_history_by_item_key(
181
- self,
182
- hosts: list[dict],
183
- time_from: int,
184
- time_till: int,
185
- item_key: str,
186
- data_type: int = 3,
187
- ) -> list[dict]:
188
-
189
- if not hosts:
190
- return []
191
-
192
- hostids = [h["hostid"] for h in hosts]
193
- item_map = self._get_items_by_key(hostids, item_key)
194
-
195
- if not item_map:
196
- return []
197
-
198
- history = self._get_history(
199
- list(item_map.values()),
200
- time_from,
201
- time_till,
202
- data_type,
203
- )
204
-
205
- history_by_item = {}
206
- for h in history:
207
- history_by_item.setdefault(h["itemid"], []).append(h)
208
-
209
- result: list[dict] = []
210
-
211
- for host in hosts:
212
- itemid = item_map.get(host["hostid"])
213
- if not itemid:
214
- continue
215
-
216
- host = host.copy()
217
- host["itemkey"] = item_key
218
- host["itemid"] = itemid
219
- host["history"] = sort_dicts(
220
- history_by_item.get(itemid, []),
221
- "clock",
222
- )
223
- result.append(host)
224
-
225
- return result
226
-
227
- # -------------------------------------------------------------------------
228
- # Create Objects
229
- # -------------------------------------------------------------------------
230
-
231
- def _get_host_by_ip(self, ip: str) -> tuple[str, ...]:
232
- result = self.request(
233
- "hostinterface.get",
234
- {
235
- "filter": {"ip": ip},
236
- "selectHosts": ["host"],
237
- },
238
- )
239
-
240
- if not result:
241
- raise ZabbixError(f"Host not found for IP {ip}")
242
-
243
- host = result[0]["hosts"][0]
244
- return host["host"], result[0]["hostid"], result[0]["interfaceid"]
245
-
246
- def create_item(self, hostid: str, interfaceid: str, item: dict) -> str:
247
- params = {
248
- "hostid": hostid,
249
- "interfaceid": interfaceid,
250
- "type": 7,
251
- "value_type": 3,
252
- "delay": "1m",
253
- "history": "7d",
254
- "trends": "7d",
255
- } | item
256
-
257
- result = self.request("item.create", params)
258
- return result["itemids"][0]
259
-
260
- def create_trigger(self, host: str, trigger: dict) -> None:
261
- trigger = trigger.copy()
262
- trigger["expression"] = trigger["expression"].format(host=host)
263
-
264
- self.request("trigger.create", [trigger])
265
-
266
- def create_graph(self, itemid: str, graph: dict) -> None:
267
- params = {
268
- "width": 900,
269
- "height": 200,
270
- "gitems": [{"itemid": itemid, "color": "0040FF"}],
271
- } | graph
272
-
273
- self.request("graph.create", params)
274
-
275
- def create_object(
276
- self,
277
- ips: list[str],
278
- *,
279
- item: dict | None = None,
280
- trigger: dict | None = None,
281
- graph: dict | None = None,
282
- ) -> None:
283
-
284
- for ip in ips:
285
- host, hostid, interfaceid = self._get_host_by_ip(ip)
286
-
287
- itemid: str | None = None
288
-
289
- if item:
290
- itemid = self.create_item(hostid, interfaceid, item)
291
-
292
- if trigger:
293
- self.create_trigger(host, trigger)
294
-
295
- if graph and itemid:
296
- self.create_graph(itemid, graph)