ezKit 3.0.74__tar.gz → 3.0.76__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.74
3
+ Version: 3.0.76
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -515,7 +515,7 @@ class Database:
515
515
 
516
516
  Returns:
517
517
  未启用序列化时返回 `CursorResult` 或 `ScalarResult`;
518
- 启用时返回字典列表或标量列表;执行或结果处理失败时记录错误并返回 None。
518
+ 启用时返回字典列表或标量列表;语句不返回行时返回空列表;执行或结果处理失败时记录错误并返回 None。
519
519
  未序列化的结果在 Session 关闭后返回,需要注意其生命周期;
520
520
  如需在Session 生命周期外使用结果,应启用序列化。
521
521
  """
@@ -534,9 +534,17 @@ class Database:
534
534
 
535
535
  with self._get_db() as session:
536
536
 
537
- result: CursorResult | ScalarResult = (
538
- session.scalars(stmt, execution_params, **kwargs) if scalars else session.execute(stmt, execution_params, **kwargs)
539
- )
537
+ raw_result: CursorResult = session.execute(stmt, execution_params, **kwargs)
538
+
539
+ # 序列化前检查 returns_rows
540
+ # INSERT、DELETE 等无返回行的语句,
541
+ # 执行成功时,返回 [],不会再调用 .mappings().all() 或 .all(),避免触发 ResourceClosedError。
542
+ # 执行失败时,会触发 Exception,返回 None。
543
+ if serialize and not raw_result.returns_rows:
544
+ logger.success(f"{info} | success")
545
+ return []
546
+
547
+ result: CursorResult | ScalarResult = raw_result.scalars() if scalars else raw_result
540
548
 
541
549
  if serialize and isinstance(result, CursorResult):
542
550
  rows = result.mappings().all()
@@ -1058,7 +1066,7 @@ class AsyncDatabase:
1058
1066
 
1059
1067
  Returns:
1060
1068
  未启用序列化时返回 `CursorResult` 或 `ScalarResult`;
1061
- 启用时返回字典列表或标量列表;执行或结果处理失败时记录错误并返回 None。
1069
+ 启用时返回字典列表或标量列表;语句不返回行时返回空列表;执行或结果处理失败时记录错误并返回 None。
1062
1070
  未序列化的结果在 Session 关闭后返回,需要注意其生命周期;
1063
1071
  如需在Session 生命周期外使用结果,应启用序列化。
1064
1072
  """
@@ -1078,11 +1086,17 @@ class AsyncDatabase:
1078
1086
  async with self._get_db() as session:
1079
1087
 
1080
1088
  # AsyncSession.execute() 的类型标注较宽,运行时结果仍按 CursorResult 处理。
1081
- result: CursorResult | ScalarResult = (
1082
- await session.scalars(stmt, execution_params, **kwargs)
1083
- if scalars
1084
- else await session.execute(stmt, execution_params, **kwargs) # type: ignore
1085
- )
1089
+ raw_result: CursorResult = await session.execute(stmt, execution_params, **kwargs) # type: ignore
1090
+
1091
+ # 序列化前检查 returns_rows
1092
+ # INSERT、DELETE 等无返回行的语句,
1093
+ # 执行成功时,返回 [],不会再调用 .mappings().all() 或 .all(),避免触发 ResourceClosedError。
1094
+ # 执行失败时,会触发 Exception,返回 None。
1095
+ if serialize and not raw_result.returns_rows:
1096
+ logger.success(f"{info} | success")
1097
+ return []
1098
+
1099
+ result: CursorResult | ScalarResult = raw_result.scalars() if scalars else raw_result
1086
1100
 
1087
1101
  if serialize and isinstance(result, CursorResult):
1088
1102
  rows = result.mappings().all()
@@ -3,6 +3,7 @@
3
3
  import logging
4
4
  import sys
5
5
  from collections.abc import Awaitable, Callable
6
+ from dataclasses import dataclass
6
7
  from datetime import time
7
8
  from os import environ
8
9
  from pathlib import Path
@@ -136,30 +137,41 @@ class InterceptHandler(logging.Handler):
136
137
  # --------------------------------------------------------------------------------------------------
137
138
 
138
139
 
140
+ @dataclass(slots=True)
141
+ class DownloadFileConfig:
142
+ """下载文件选项"""
143
+
144
+ download: bool = False
145
+ response: FastAPIResponse | None = None
146
+
147
+
139
148
  async def api_execute(
140
149
  operation: Callable[[Any], Any | Awaitable[Any]],
141
150
  params_object: Any,
142
151
  params_type: str = "text",
143
- download_file: bool = False,
144
- response: FastAPIResponse | None = None,
152
+ download_file: DownloadFileConfig | None = None,
145
153
  ) -> JSONResponse | FileResponse | None:
146
- """API Execution"""
147
-
148
- # param: operation 函数
149
- # param: params_object 参数对象
150
- # param: params_type 参数类型
151
- # return: JSONResponse
152
- #
153
- # params_object:
154
- #
155
- # 默认解析 Request
156
- #
157
- # 如果不是 Request, 则直接使用 params_object
158
- # 即: 直接将 params_object 传递给 operation 函数
159
- #
160
- # params_type: text(默认), json, form
161
- #
162
- # download_file 和 response 必须同时存在
154
+ """解析请求参数并执行常规 API 操作或文件下载。
155
+
156
+ 常规操作通过 await 调用,并将结果包装为 JSON Response;
157
+ 配置中的 download_file 的 download 为 True 时,同步调用 operation,
158
+ 成功时直接返回 FileResponse,
159
+ 失败时通过配置中的 response 将 HTTP 状态码设为 400。
160
+
161
+ Args:
162
+ operation: 接收解析后参数的同步或异步操作函数。
163
+ params_object: FastAPI Request 或直接传入的字符串参数。
164
+ params_type: 请求参数格式,可选 `text`、`json` 或 `form`。
165
+ download_file: 可选执行配置。`download=True` 时必须提供 response,用于设置下载失败状态码。
166
+
167
+ Returns:
168
+ 常规模式返回 JSONResponse;
169
+ 下载成功时返回 FileResponse;
170
+ 下载失败时设置 HTTP 400 并返回 None。
171
+ 常规模式中的参数错误、执行失败或异常均返回统一 JSON 错误响应。
172
+ """
173
+
174
+ download_response: FastAPIResponse | None = None
163
175
 
164
176
  try:
165
177
 
@@ -169,9 +181,10 @@ async def api_execute(
169
181
  if params_type not in {"text", "json", "form"}:
170
182
  return Response(code=1001, message="Invalid parameter type")
171
183
 
172
- # download_file 和 response 必须同时存在
173
- if download_file and response is None:
174
- return Response(code=1002, message="Missing response parameter")
184
+ if download_file is not None and download_file.download:
185
+ if not isinstance(download_file.response, FastAPIResponse):
186
+ return Response(code=1002, message="Invalid response parameter")
187
+ download_response = download_file.response
175
188
 
176
189
  if isinstance(params_object, Request):
177
190
  if params_type == "json":
@@ -187,31 +200,27 @@ async def api_execute(
187
200
  logger.debug(f"parameters:\n----------\n\n{data}\n\n----------")
188
201
 
189
202
  if data in ("", {}, []) or (isinstance(data, FormData) and not data):
190
-
191
- # 处理下载文件错误
192
- if download_file and response is not None:
193
- response.status_code = status.HTTP_400_BAD_REQUEST
203
+ if download_response is not None:
204
+ download_response.status_code = status.HTTP_400_BAD_REQUEST
194
205
  return None
195
-
196
- # 处理常规数据错误
197
206
  return Response(code=1003, message="Parameters cannot be empty")
198
207
 
199
- result = operation(data) if download_file else await operation(data)
208
+ # 下载文件请求使用同步调用,常规请求使用异步调用
209
+ result = operation(data) if download_response is not None else await operation(data)
200
210
 
201
- if DEBUG:
211
+ if DEBUG and download_response is None:
202
212
  logger.debug(f"result:\n----------\n\n{result}\n\n----------")
203
213
 
204
214
  if result is None:
205
-
206
- # 处理下载文件错误
207
- if download_file and response is not None:
208
- response.status_code = status.HTTP_400_BAD_REQUEST
215
+ if download_response is not None:
216
+ download_response.status_code = status.HTTP_400_BAD_REQUEST
209
217
  return None
210
-
211
- # 处理常规数据错误
212
218
  return Response(code=1004, message="Execution failed. Check the parameters or service.")
213
219
 
214
- return cast(FileResponse, result) if download_file else cast(JSONResponse, Response(data=result))
220
+ if download_response is not None:
221
+ return cast(FileResponse, result)
222
+
223
+ return Response(data=result)
215
224
 
216
225
  except Exception as e:
217
226
 
@@ -220,10 +229,8 @@ async def api_execute(
220
229
  else:
221
230
  logger.error(e)
222
231
 
223
- # 处理下载文件错误
224
- if download_file and response is not None:
225
- response.status_code = status.HTTP_400_BAD_REQUEST
232
+ if download_response is not None:
233
+ download_response.status_code = status.HTTP_400_BAD_REQUEST
226
234
  return None
227
235
 
228
- # 处理常规数据错误
229
236
  return Response(code=400, message=str(e))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ezKit
3
- Version: 3.0.74
3
+ Version: 3.0.76
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -4,7 +4,7 @@ from setuptools import find_packages, setup
4
4
 
5
5
  setup(
6
6
  name="ezKit",
7
- version="3.0.74",
7
+ version="3.0.76",
8
8
  author="septvean",
9
9
  author_email="septvean@gmail.com",
10
10
  description="Easy Kit",
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes