ezKit 3.0.1__tar.gz → 3.0.3__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ezKit
3
- Version: 3.0.1
3
+ Version: 3.0.3
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -28,7 +28,9 @@ class Database:
28
28
  def _get_db(self):
29
29
  """common database connection context manager"""
30
30
  # 公用数据库连接上下文管理器
31
+
31
32
  session = self._db_session()
33
+
32
34
  try:
33
35
  yield session # 将 session 传递给 with 语句
34
36
  session.commit() # 如果没有报错,自动提交(可选,不需要自动提交可以删掉这行)
@@ -67,34 +69,47 @@ class Database:
67
69
  logger.info(f"{info} | start")
68
70
 
69
71
  try:
72
+
70
73
  stmt = text(statement) if isinstance(statement, str) else statement
74
+
71
75
  with self._get_db() as session:
72
76
  result: CursorResult | ScalarResult = session.scalars(stmt) if scalars else session.execute(stmt)
73
77
  logger.success(f"{info} | success")
74
78
  return result
79
+
75
80
  except Exception as e:
81
+
76
82
  logger.error(f"{info} | error")
83
+
77
84
  if DEBUG:
78
85
  logger.exception(e)
79
86
  else:
80
87
  logger.error(e)
88
+
81
89
  return None
82
90
 
83
91
  # 连接测试
84
92
  def connection_test(self) -> bool:
85
93
  """database connection test"""
86
94
 
87
- logger.info("database connection test | start")
95
+ info: str = "database connection test"
96
+
97
+ logger.info(f"{info} | start")
88
98
 
89
99
  try:
100
+
90
101
  with self._get_db() as session:
91
102
  session.execute(text("SELECT 1;"))
92
- logger.success("database connection test | success")
103
+ logger.success(f"{info} | success")
93
104
  return True
105
+
94
106
  except Exception as e:
95
- logger.error("database connection test | error")
107
+
108
+ logger.error(f"{info} | error")
109
+
96
110
  if DEBUG:
97
111
  logger.exception(e)
98
112
  else:
99
113
  logger.error(e)
114
+
100
115
  return False
@@ -0,0 +1,206 @@
1
+ from email.header import Header
2
+ from email.mime.image import MIMEImage
3
+ from email.mime.multipart import MIMEMultipart
4
+ from email.mime.text import MIMEText
5
+ from email.utils import formataddr, parseaddr
6
+ from os import environ
7
+ from typing import Optional, TypedDict
8
+
9
+ import aiosmtplib
10
+ from loguru import logger
11
+
12
+ from . import utils
13
+
14
+ DEBUG = environ.get("DEBUG")
15
+
16
+
17
+ class TypedSMTP(TypedDict):
18
+ """smtp type"""
19
+
20
+ server: str
21
+ port: int
22
+ # tls: bool
23
+
24
+
25
+ class TypedSender(TypedDict):
26
+ """sender type"""
27
+
28
+ name: str
29
+ address: str
30
+ password: str
31
+
32
+
33
+ class TypedBody(TypedDict, total=False):
34
+ """body type"""
35
+
36
+ content: str
37
+ type: Optional[str] # "plain", "html", or "file"
38
+
39
+
40
+ def format_parse(s: str) -> str:
41
+ """格式化邮件地址"""
42
+ _name, _addr = parseaddr(s)
43
+ return formataddr((Header(_name, "utf-8").encode(), _addr))
44
+
45
+
46
+ async def sendemail(
47
+ smtp: TypedSMTP,
48
+ sender: TypedSender,
49
+ recipients: str | list[str],
50
+ subject: str,
51
+ body: TypedBody,
52
+ images: Optional[list[dict]] = None,
53
+ ) -> bool:
54
+ """异步发送邮件"""
55
+
56
+ # smtp SMTP信息
57
+ #
58
+ # server SMTP地址
59
+ # port SMTP端口
60
+ # tls 是否使用TLS
61
+ #
62
+ # sender 发件人信息
63
+ #
64
+ # name 发件人名称
65
+ # address 发件人邮箱地址
66
+ # password 发件人邮箱密码(SMTP)
67
+ #
68
+ # recipients 收件人(或列表)
69
+ #
70
+ # subject 邮件主题
71
+ #
72
+ # body 邮件主体
73
+ #
74
+ # content 内容
75
+ # type 类型 (默认 plain, 或者 file, 或者 html)
76
+ #
77
+ # images 图片列表(可选)
78
+ #
79
+ # cid 图片CID
80
+ # path 图片路径
81
+
82
+ info: str = "send email"
83
+
84
+ logger.info(f"{info} | start")
85
+
86
+ try:
87
+
88
+ # 邮件主体构建
89
+
90
+ if not isinstance(body, dict) or "content" not in body:
91
+ logger.error(f"{info} | body error")
92
+ return False
93
+
94
+ message: MIMEMultipart = MIMEMultipart()
95
+
96
+ body_content = body["content"]
97
+
98
+ if not isinstance(body_content, str):
99
+ logger.error(f"{info} | body content error: {body_content}")
100
+ return False
101
+
102
+ body_type = body.get("type", "plain")
103
+
104
+ if body_type == "file":
105
+ # 从文本文件读取内容
106
+ with open(body_content, "r", encoding="utf-8") as file:
107
+ message.attach(MIMEText(file.read(), "plain", "utf-8"))
108
+ elif body_type == "html":
109
+ # 从HTML文件读取内容
110
+ message = MIMEMultipart("related")
111
+ with open(body_content, "r", encoding="utf-8") as file:
112
+ message.attach(MIMEText(file.read(), "html", "utf-8"))
113
+ else:
114
+ # 纯文本内容
115
+ message.attach(MIMEText(body_content, "plain", "utf-8"))
116
+
117
+ # ------------------------------------------------------------------------------------------
118
+
119
+ # 设置 SMTP 信息
120
+
121
+ smtp_host = smtp.get("server")
122
+ smtp_port = smtp.get("port")
123
+ # smtp_tls = smtp.get("tls", False)
124
+
125
+ if not smtp_host or not smtp_port:
126
+ logger.error(f"{info} | SMTP config error")
127
+ return False
128
+
129
+ # ------------------------------------------------------------------------------------------
130
+
131
+ # 设置发件人信息
132
+
133
+ sender_name = sender.get("name")
134
+ sender_address = sender.get("address")
135
+ sender_password = sender.get("password")
136
+
137
+ if not sender_name or not sender_address or not sender_password:
138
+ logger.error(f"{info} | sender config error")
139
+ return False
140
+
141
+ message["From"] = formataddr((sender_name, sender_address))
142
+
143
+ # ------------------------------------------------------------------------------------------
144
+
145
+ # 设置收件人
146
+ if isinstance(recipients, str):
147
+ message["To"] = format_parse(recipients)
148
+ elif isinstance(recipients, list):
149
+ message["To"] = ", ".join([format_parse(r) for r in recipients])
150
+ else:
151
+ logger.error(f"{info} | recipients error")
152
+ return False
153
+
154
+ # ------------------------------------------------------------------------------------------
155
+
156
+ # 设置邮件主题
157
+ if not isinstance(subject, str):
158
+ logger.error(f"{info} | subject error")
159
+ return False
160
+
161
+ message["Subject"] = subject
162
+
163
+ # ------------------------------------------------------------------------------------------
164
+
165
+ # 处理图片
166
+ if images:
167
+ for image in images:
168
+ try:
169
+ if utils.check_path_type(image.get("path", ""), "file"):
170
+ with open(image["path"], "rb") as _image_file:
171
+ mime_image = MIMEImage(_image_file.read())
172
+ mime_image.add_header("Content-ID", f"<{image['cid']}>")
173
+ message.attach(mime_image)
174
+ except Exception as e:
175
+ logger.exception(e)
176
+ return False
177
+
178
+ # ------------------------------------------------------------------------------------------
179
+
180
+ # 使用 aiomail 发送邮件
181
+ async with aiosmtplib.SMTP(hostname=smtp_host, port=smtp_port) as smtp_server:
182
+
183
+ # if smtp_tls:
184
+ # await smtp_server.starttls()
185
+
186
+ await smtp_server.login(sender_address, sender_password)
187
+ await smtp_server.sendmail(sender_address, recipients, message.as_string())
188
+
189
+ logger.success(f"{info} | success")
190
+
191
+ return True
192
+
193
+ except Exception as e:
194
+
195
+ # 忽略腾讯邮箱返回的异常
196
+ if e.args == (-1, b"\x00\x00\x00"):
197
+ return True
198
+
199
+ logger.error(f"{info} | error")
200
+
201
+ if DEBUG:
202
+ logger.exception(e)
203
+ else:
204
+ logger.error(e)
205
+
206
+ return False
@@ -0,0 +1,192 @@
1
+ """Utils Library"""
2
+
3
+ import time
4
+ from functools import wraps
5
+ from os import environ
6
+ from pathlib import Path
7
+ from typing import Any, Callable, ParamSpec, TypeVar
8
+
9
+ from loguru import logger
10
+
11
+ # --------------------------------------------------------------------------------------------------
12
+
13
+ DEBUG = environ.get("DEBUG")
14
+
15
+ # --------------------------------------------------------------------------------------------------
16
+
17
+
18
+ def isTrue(target: object, typeClass: Any) -> bool:
19
+ """检查对象是否为真"""
20
+
21
+ # 常见布尔类型:
22
+ #
23
+ # Boolean bool False
24
+ # Numbers int/float 0/0.0
25
+ # String str ""
26
+ # List list/tuple/set []/()/{}
27
+ # Dictionary dict {}
28
+ # Set set set()
29
+ #
30
+ # 查看变量类型: type(x)
31
+ #
32
+ # 判断变量类型: isinstance(x, str)
33
+ #
34
+ # 函数使用 callable(func) 判断
35
+ #
36
+ # 判断多个类型:
37
+ #
38
+ # isTrue("abc", (str, int))
39
+ # isTrue("abc", (str | int))
40
+ #
41
+ # all() 用于检查一个可迭代对象(如列表、元组、集合等)中的 所有 元素是否为 真值 (truthy), 所有元素为真, 返回 True
42
+ # any() 用于检查一个可迭代对象(如列表、元组、集合等)中的 某个 元素是否为 真值 (truthy), 某个元素为真, 返回 True
43
+ # 与 all() 作用相反的 not any(), 可以用来检查所有元素是否为 假值 (falsy), any() 中所有元素为假, not any() 返回 True
44
+ #
45
+ # return target not in [False, None, 0, 0.0, '', (), [], {}, set(), {*()}, {*[]}, {*{}}, {*set()}]
46
+
47
+ try:
48
+
49
+ return bool(isinstance(target, typeClass) and target)
50
+
51
+ except Exception as e:
52
+
53
+ if DEBUG:
54
+ logger.exception(e)
55
+ else:
56
+ logger.error(e)
57
+
58
+ return False
59
+
60
+
61
+ # --------------------------------------------------------------------------------------------------
62
+
63
+
64
+ P = ParamSpec("P")
65
+ R = TypeVar("R")
66
+
67
+
68
+ def retry_decorator(times: int = 3, delay: float = 1.0):
69
+ """重试装饰器"""
70
+
71
+ def decorator(func: Callable[P, R]) -> Callable[P, R | bool]:
72
+ @wraps(func)
73
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | bool:
74
+ max_times = max(1, times)
75
+ for attempt in range(max_times):
76
+ try:
77
+ return func(*args, **kwargs)
78
+ except Exception as e:
79
+ if DEBUG:
80
+ logger.exception(e)
81
+ else:
82
+ logger.error(e)
83
+
84
+ if attempt < (max_times - 1):
85
+ time.sleep(delay)
86
+ else:
87
+ return False
88
+ return False
89
+
90
+ return wrapper
91
+
92
+ return decorator
93
+
94
+
95
+ # --------------------------------------------------------------------------------------------------
96
+
97
+
98
+ def check_path_type(path_object: str | Path, path_type: str) -> bool:
99
+ """检查路径类型"""
100
+
101
+ try:
102
+
103
+ _path_object: Path = Path(path_object) if not isinstance(path_object, Path) else path_object
104
+
105
+ # 文件不存在的情况
106
+ if not _path_object.exists():
107
+ return False
108
+
109
+ # 根据 path_type 判断路径类型
110
+ # 如果 path_type 不匹配任何已知类型,返回 False
111
+ match path_type:
112
+ case "absolute":
113
+ return _path_object.is_absolute()
114
+ case "block_device":
115
+ return _path_object.is_block_device()
116
+ case "dir":
117
+ return _path_object.is_dir()
118
+ case "fifo":
119
+ return _path_object.is_fifo()
120
+ case "file":
121
+ return _path_object.is_file()
122
+ case "mount":
123
+ return _path_object.is_mount()
124
+ case "socket":
125
+ return _path_object.is_socket()
126
+ case "symlink":
127
+ return _path_object.is_symlink()
128
+ case _:
129
+ return False
130
+
131
+ except Exception as e:
132
+
133
+ if DEBUG:
134
+ logger.exception(e)
135
+ else:
136
+ logger.error(e)
137
+
138
+ return False
139
+
140
+
141
+ # --------------------------------------------------------------------------------------------------
142
+
143
+
144
+ def realpath(path: str, **kwargs) -> str | None:
145
+ """获取对象真实路径"""
146
+
147
+ try:
148
+
149
+ return str(Path(path, **kwargs).resolve()) if isTrue(path, str) else None
150
+
151
+ except Exception as e:
152
+
153
+ if DEBUG:
154
+ logger.exception(e)
155
+ else:
156
+ logger.error(e)
157
+
158
+ return None
159
+
160
+
161
+ def current_dir(path: str, **kwargs) -> str | None:
162
+ """获取对象所在目录"""
163
+
164
+ try:
165
+
166
+ return str(Path(path, **kwargs).parent.resolve()) if isTrue(path, str) else None
167
+
168
+ except Exception as e:
169
+
170
+ if DEBUG:
171
+ logger.exception(e)
172
+ else:
173
+ logger.error(e)
174
+
175
+ return None
176
+
177
+
178
+ def parent_dir(path: str, **kwargs) -> str | None:
179
+ """获取对象所在目录的父目录"""
180
+
181
+ try:
182
+
183
+ return str(Path(path, **kwargs).parent.parent.resolve()) if isTrue(path, str) else None
184
+
185
+ except Exception as e:
186
+
187
+ if DEBUG:
188
+ logger.exception(e)
189
+ else:
190
+ logger.error(e)
191
+
192
+ return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ezKit
3
- Version: 3.0.1
3
+ Version: 3.0.3
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -5,6 +5,7 @@ pyproject.toml
5
5
  setup.py
6
6
  ezKit/__init__.py
7
7
  ezKit/database.py
8
+ ezKit/sendemail.py
8
9
  ezKit/utils.py
9
10
  ezKit.egg-info/PKG-INFO
10
11
  ezKit.egg-info/SOURCES.txt
@@ -4,7 +4,7 @@ from setuptools import find_packages, setup
4
4
 
5
5
  setup(
6
6
  name="ezKit",
7
- version="3.0.1",
7
+ version="3.0.3",
8
8
  author="septvean",
9
9
  author_email="septvean@gmail.com",
10
10
  description="Easy Kit",
@@ -1,51 +0,0 @@
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
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes