ezKit 3.0.0__tar.gz → 3.0.2__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.0
3
+ Version: 3.0.2
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -26,8 +26,11 @@ class Database:
26
26
 
27
27
  @contextmanager
28
28
  def _get_db(self):
29
- """公用数据库连接上下文管理器"""
29
+ """common database connection context manager"""
30
+ # 公用数据库连接上下文管理器
31
+
30
32
  session = self._db_session()
33
+
31
34
  try:
32
35
  yield session # 将 session 传递给 with 语句
33
36
  session.commit() # 如果没有报错,自动提交(可选,不需要自动提交可以删掉这行)
@@ -37,13 +40,26 @@ class Database:
37
40
  finally:
38
41
  session.close()
39
42
 
40
- def execute(self, statement: str | TextClause | Delete | Insert | Select | Update, scalars: bool = False) -> CursorResult | ScalarResult | None:
43
+ def execute(
44
+ self,
45
+ statement: str | TextClause | Delete | Insert | Select | Update, # SQL 语句
46
+ scalars: bool = False, # 是否使用 scalars() 方法获取结果
47
+ ) -> CursorResult | ScalarResult | None:
41
48
  """database execute statement"""
42
49
 
43
- # SQL 语句既可以是 text() 对象 也可以是 ORM 构建的 statement 对象
50
+ # statement 可以是 纯 SQL 字符串, 也可以是 text() 对象, 也可以是 ORM 构建的 statement 对象
51
+ #
52
+ # str: 会使用 text() 转换为 text() 对象
53
+ # TextClause: 已经处理好的 text() 对象, 可以直接使用
54
+ # Select, Insert, Update, Delete: ORM 构建的 statement 对象
55
+ #
56
+ # scalars: 是否使用 scalars() 方法获取结果, 适用于获取单列数据, 如果是多列数据, 使用 execute() 方法获取结果
57
+ #
58
+ # 返回值:
44
59
  #
45
- # text() 对象可以是任意 SQL 语句
46
- # statement 对象包括 select, insert, update, delete 等
60
+ # CursorResult: 返回 CursorResult 对象
61
+ # ScalarResult: 返回 ScalarResult 对象
62
+ # None: 如果发生错误, 则返回 None
47
63
 
48
64
  info: str = "database execute statement"
49
65
 
@@ -53,34 +69,47 @@ class Database:
53
69
  logger.info(f"{info} | start")
54
70
 
55
71
  try:
72
+
56
73
  stmt = text(statement) if isinstance(statement, str) else statement
74
+
57
75
  with self._get_db() as session:
58
76
  result: CursorResult | ScalarResult = session.scalars(stmt) if scalars else session.execute(stmt)
59
77
  logger.success(f"{info} | success")
60
78
  return result
79
+
61
80
  except Exception as e:
81
+
62
82
  logger.error(f"{info} | error")
83
+
63
84
  if DEBUG:
64
85
  logger.exception(e)
65
86
  else:
66
87
  logger.error(e)
88
+
67
89
  return None
68
90
 
69
91
  # 连接测试
70
92
  def connection_test(self) -> bool:
71
93
  """database connection test"""
72
94
 
73
- logger.info("database connection test | start")
95
+ info: str = "database connection test"
96
+
97
+ logger.info(f"{info} | start")
74
98
 
75
99
  try:
100
+
76
101
  with self._get_db() as session:
77
102
  session.execute(text("SELECT 1;"))
78
- logger.success("database connection test | success")
103
+ logger.success(f"{info} | success")
79
104
  return True
105
+
80
106
  except Exception as e:
81
- logger.error("database connection test | error")
107
+
108
+ logger.error(f"{info} | error")
109
+
82
110
  if DEBUG:
83
111
  logger.exception(e)
84
112
  else:
85
113
  logger.error(e)
114
+
86
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,156 @@
1
+ """Utils Library"""
2
+
3
+ from os import environ
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from loguru import logger
8
+
9
+ # --------------------------------------------------------------------------------------------------
10
+
11
+ DEBUG = environ.get("DEBUG")
12
+
13
+ # --------------------------------------------------------------------------------------------------
14
+
15
+
16
+ def isTrue(target: object, typeClass: Any) -> bool:
17
+ """检查对象是否为真"""
18
+
19
+ # 常见布尔类型:
20
+ #
21
+ # Boolean bool False
22
+ # Numbers int/float 0/0.0
23
+ # String str ""
24
+ # List list/tuple/set []/()/{}
25
+ # Dictionary dict {}
26
+ # Set set set()
27
+ #
28
+ # 查看变量类型: type(x)
29
+ #
30
+ # 判断变量类型: isinstance(x, str)
31
+ #
32
+ # 函数使用 callable(func) 判断
33
+ #
34
+ # 判断多个类型:
35
+ #
36
+ # isTrue("abc", (str, int))
37
+ # isTrue("abc", (str | int))
38
+ #
39
+ # all() 用于检查一个可迭代对象(如列表、元组、集合等)中的 所有 元素是否为 真值 (truthy), 所有元素为真, 返回 True
40
+ # any() 用于检查一个可迭代对象(如列表、元组、集合等)中的 某个 元素是否为 真值 (truthy), 某个元素为真, 返回 True
41
+ # 与 all() 作用相反的 not any(), 可以用来检查所有元素是否为 假值 (falsy), any() 中所有元素为假, not any() 返回 True
42
+ #
43
+ # return target not in [False, None, 0, 0.0, '', (), [], {}, set(), {*()}, {*[]}, {*{}}, {*set()}]
44
+
45
+ try:
46
+
47
+ return bool(isinstance(target, typeClass) and target)
48
+
49
+ except Exception as e:
50
+
51
+ if DEBUG:
52
+ logger.exception(e)
53
+ else:
54
+ logger.error(e)
55
+
56
+ return False
57
+
58
+
59
+ # --------------------------------------------------------------------------------------------------
60
+
61
+
62
+ def check_path_type(path_object: str | Path, path_type: str) -> bool:
63
+ """检查路径类型"""
64
+
65
+ try:
66
+
67
+ _path_object: Path = Path(path_object) if not isinstance(path_object, Path) else path_object
68
+
69
+ # 文件不存在的情况
70
+ if not _path_object.exists():
71
+ return False
72
+
73
+ # 根据 path_type 判断路径类型
74
+ # 如果 path_type 不匹配任何已知类型,返回 False
75
+ match path_type:
76
+ case "absolute":
77
+ return _path_object.is_absolute()
78
+ case "block_device":
79
+ return _path_object.is_block_device()
80
+ case "dir":
81
+ return _path_object.is_dir()
82
+ case "fifo":
83
+ return _path_object.is_fifo()
84
+ case "file":
85
+ return _path_object.is_file()
86
+ case "mount":
87
+ return _path_object.is_mount()
88
+ case "socket":
89
+ return _path_object.is_socket()
90
+ case "symlink":
91
+ return _path_object.is_symlink()
92
+ case _:
93
+ return False
94
+
95
+ except Exception as e:
96
+
97
+ if DEBUG:
98
+ logger.exception(e)
99
+ else:
100
+ logger.error(e)
101
+
102
+ return False
103
+
104
+
105
+ # --------------------------------------------------------------------------------------------------
106
+
107
+
108
+ def realpath(path: str, **kwargs) -> str | None:
109
+ """获取对象真实路径"""
110
+
111
+ try:
112
+
113
+ return str(Path(path, **kwargs).resolve()) if isTrue(path, str) else None
114
+
115
+ except Exception as e:
116
+
117
+ if DEBUG:
118
+ logger.exception(e)
119
+ else:
120
+ logger.error(e)
121
+
122
+ return None
123
+
124
+
125
+ def current_dir(path: str, **kwargs) -> str | None:
126
+ """获取对象所在目录"""
127
+
128
+ try:
129
+
130
+ return str(Path(path, **kwargs).parent.resolve()) if isTrue(path, str) else None
131
+
132
+ except Exception as e:
133
+
134
+ if DEBUG:
135
+ logger.exception(e)
136
+ else:
137
+ logger.error(e)
138
+
139
+ return None
140
+
141
+
142
+ def parent_dir(path: str, **kwargs) -> str | None:
143
+ """获取对象所在目录的父目录"""
144
+
145
+ try:
146
+
147
+ return str(Path(path, **kwargs).parent.parent.resolve()) if isTrue(path, str) else None
148
+
149
+ except Exception as e:
150
+
151
+ if DEBUG:
152
+ logger.exception(e)
153
+ else:
154
+ logger.error(e)
155
+
156
+ return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ezKit
3
- Version: 3.0.0
3
+ Version: 3.0.2
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.0",
7
+ version="3.0.2",
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