sycommon-python-lib 0.1.2__py3-none-any.whl → 0.1.3__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 sycommon-python-lib might be problematic. Click here for more details.
- sycommon/middleware/middleware.py +21 -18
- sycommon/models/base_http.py +99 -0
- sycommon/services.py +48 -4
- {sycommon_python_lib-0.1.2.dist-info → sycommon_python_lib-0.1.3.dist-info}/METADATA +1 -1
- {sycommon_python_lib-0.1.2.dist-info → sycommon_python_lib-0.1.3.dist-info}/RECORD +7 -6
- {sycommon_python_lib-0.1.2.dist-info → sycommon_python_lib-0.1.3.dist-info}/WHEEL +0 -0
- {sycommon_python_lib-0.1.2.dist-info → sycommon_python_lib-0.1.3.dist-info}/top_level.txt +0 -0
|
@@ -8,29 +8,32 @@ from sycommon.middleware.traceid import setup_trace_id_handler
|
|
|
8
8
|
from sycommon.health.health_check import setup_health_handler
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
# 设置请求超时中间件
|
|
13
|
-
app = setup_request_timeout_middleware(app, config)
|
|
11
|
+
class Middleware:
|
|
14
12
|
|
|
15
|
-
|
|
16
|
-
|
|
13
|
+
@classmethod
|
|
14
|
+
def setup_middleware(cls, app, config: dict):
|
|
15
|
+
# 设置请求超时中间件
|
|
16
|
+
app = setup_request_timeout_middleware(app, config)
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
# 设置异常处理
|
|
19
|
+
app = setup_exception_handler(app, config)
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
# 设置 trace_id 处理中间件
|
|
22
|
+
app = setup_trace_id_handler(app)
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
# 设置内存监控中间件
|
|
25
|
+
# app = setup_monitor_memory_middleware(app)
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
# 设置cors
|
|
28
|
+
# app = setup_cors_handler(app)
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
# 健康检查
|
|
31
|
+
app = setup_health_handler(app)
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
# ping
|
|
34
|
+
app = setup_ping_handler(app)
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
# 添加mq中间件
|
|
37
|
+
# app = setup_mq_middleware(app)
|
|
38
|
+
|
|
39
|
+
return app
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from typing import TypeVar, Any, Generic
|
|
2
|
+
from pydantic import BaseModel, Field
|
|
3
|
+
from fastapi.responses import JSONResponse
|
|
4
|
+
from fastapi import status
|
|
5
|
+
|
|
6
|
+
# 修改泛型约束,支持任意类型(包括基础类型和BaseModel)
|
|
7
|
+
T = TypeVar('T')
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BaseResponseModel(BaseModel, Generic[T]):
|
|
11
|
+
"""基础响应模型,支持多种数据类型(包括字符串、字典和Pydantic模型)"""
|
|
12
|
+
code: int = Field(default=0, description="业务响应码,成功0,失败非0")
|
|
13
|
+
message: str = Field(default="success", description="业务响应信息")
|
|
14
|
+
data: T | None = Field(default=None, description="业务响应数据,支持任意类型")
|
|
15
|
+
traceId: str | None = Field(default=None, description="请求链路追踪ID")
|
|
16
|
+
|
|
17
|
+
class Config:
|
|
18
|
+
arbitrary_types_allowed = True
|
|
19
|
+
from_attributes = True
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_response_content(
|
|
23
|
+
data: T | Any = None,
|
|
24
|
+
code: int = 0,
|
|
25
|
+
message: str = "success"
|
|
26
|
+
) -> dict:
|
|
27
|
+
"""
|
|
28
|
+
只构建响应内容的字典部分
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
data: 响应数据(支持字符串、字典、Pydantic模型等)
|
|
32
|
+
code: 业务响应码
|
|
33
|
+
message: 响应信息
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
响应内容字典,格式为{"code": int, "message": str, "data": Any}
|
|
37
|
+
"""
|
|
38
|
+
response = BaseResponseModel(
|
|
39
|
+
code=code,
|
|
40
|
+
message=message,
|
|
41
|
+
data=data
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if isinstance(response.data, BaseModel):
|
|
45
|
+
return {
|
|
46
|
+
"code": response.code,
|
|
47
|
+
"message": response.message,
|
|
48
|
+
"data": response.data.model_dump()
|
|
49
|
+
}
|
|
50
|
+
else:
|
|
51
|
+
return response.model_dump()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def create_response(
|
|
55
|
+
data: T | Any = None,
|
|
56
|
+
code: int = 0,
|
|
57
|
+
message: str = "success",
|
|
58
|
+
status_code: int = status.HTTP_200_OK
|
|
59
|
+
) -> JSONResponse:
|
|
60
|
+
"""创建完整的JSONResponse响应"""
|
|
61
|
+
content = build_response_content(data=data, code=code, message=message)
|
|
62
|
+
return JSONResponse(
|
|
63
|
+
content=content,
|
|
64
|
+
status_code=status_code
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def success_response(data: T | Any = None, message: str = "success") -> JSONResponse:
|
|
69
|
+
"""快捷创建成功响应"""
|
|
70
|
+
return create_response(data=data, message=message)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def error_response(
|
|
74
|
+
message: str = "error",
|
|
75
|
+
code: int = 1,
|
|
76
|
+
data: T | Any = None,
|
|
77
|
+
status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
78
|
+
) -> JSONResponse:
|
|
79
|
+
"""快捷创建错误响应"""
|
|
80
|
+
return create_response(
|
|
81
|
+
data=data,
|
|
82
|
+
code=code,
|
|
83
|
+
message=message,
|
|
84
|
+
status_code=status_code
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def success_content(data: T | Any = None, message: str = "success") -> dict:
|
|
89
|
+
"""只构建成功响应的内容字典"""
|
|
90
|
+
return build_response_content(data=data, message=message)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def error_content(
|
|
94
|
+
message: str = "error",
|
|
95
|
+
code: int = 1,
|
|
96
|
+
data: T | Any = None
|
|
97
|
+
) -> dict:
|
|
98
|
+
"""只构建错误响应的内容字典"""
|
|
99
|
+
return build_response_content(data=data, code=code, message=message)
|
sycommon/services.py
CHANGED
|
@@ -2,7 +2,10 @@ from typing import Any, Callable, Dict, List, Tuple, Union, Optional, Awaitable
|
|
|
2
2
|
import asyncio
|
|
3
3
|
import logging
|
|
4
4
|
from contextlib import asynccontextmanager
|
|
5
|
+
from dotenv import load_dotenv
|
|
6
|
+
from fastapi import FastAPI
|
|
5
7
|
from pydantic import BaseModel
|
|
8
|
+
import yaml
|
|
6
9
|
from sycommon.config.Config import SingletonMeta
|
|
7
10
|
from sycommon.models.mqlistener_config import RabbitMQListenerConfig
|
|
8
11
|
from sycommon.models.mqsend_config import RabbitMQSendConfig
|
|
@@ -16,19 +19,21 @@ class Services(metaclass=SingletonMeta):
|
|
|
16
19
|
_registered_senders: List[str] = []
|
|
17
20
|
_mq_tasks: List[asyncio.Task] = []
|
|
18
21
|
_pending_setup: Optional[Callable[..., Awaitable[None]]] = None
|
|
22
|
+
_instance: Optional['Services'] = None
|
|
19
23
|
|
|
20
24
|
def __init__(self, config):
|
|
21
25
|
if not Services._config:
|
|
22
26
|
Services._config = config
|
|
23
|
-
|
|
27
|
+
Services._instance = self
|
|
24
28
|
|
|
25
29
|
@classmethod
|
|
26
30
|
def get_lifespan(cls, config):
|
|
27
31
|
"""返回 FastAPI 的 lifespan 管理器"""
|
|
32
|
+
cls._config = config
|
|
33
|
+
|
|
28
34
|
@asynccontextmanager
|
|
29
35
|
async def lifespan(app):
|
|
30
36
|
# 应用启动时初始化
|
|
31
|
-
cls._config = config
|
|
32
37
|
cls._loop = asyncio.get_running_loop()
|
|
33
38
|
cls._initialized = True
|
|
34
39
|
logging.info("Services initialized with FastAPI event loop")
|
|
@@ -51,8 +56,38 @@ class Services(metaclass=SingletonMeta):
|
|
|
51
56
|
|
|
52
57
|
return lifespan
|
|
53
58
|
|
|
54
|
-
|
|
59
|
+
@classmethod
|
|
60
|
+
def plugins(cls,
|
|
61
|
+
middleware: Optional[Tuple[Callable, FastAPI]] = None,
|
|
62
|
+
nacos_service: Optional[Callable] = None,
|
|
63
|
+
logging_service: Optional[Callable] = None,
|
|
64
|
+
database_service: Optional[Union[Tuple[Callable, str],
|
|
65
|
+
List[Tuple[Callable, str]]]] = None,
|
|
66
|
+
rabbitmq_listeners: Optional[List[RabbitMQListenerConfig]] = None,
|
|
67
|
+
rabbitmq_senders: Optional[List[RabbitMQSendConfig]] = None
|
|
68
|
+
) -> None:
|
|
69
|
+
"""
|
|
70
|
+
类方法:注册各种服务插件
|
|
71
|
+
确保单例实例存在后调用实例方法的register_plugins
|
|
72
|
+
"""
|
|
73
|
+
# 确保实例已创建
|
|
74
|
+
if not cls._instance:
|
|
75
|
+
if not cls._config:
|
|
76
|
+
raise ValueError("Services尚未初始化,请先提供配置")
|
|
77
|
+
cls._instance = Services(cls._config)
|
|
78
|
+
|
|
79
|
+
cls._instance.register_plugins(
|
|
80
|
+
middleware=middleware,
|
|
81
|
+
nacos_service=nacos_service,
|
|
82
|
+
logging_service=logging_service,
|
|
83
|
+
database_service=database_service,
|
|
84
|
+
rabbitmq_listeners=rabbitmq_listeners,
|
|
85
|
+
rabbitmq_senders=rabbitmq_senders
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def register_plugins(
|
|
55
89
|
self,
|
|
90
|
+
middleware: Optional[Tuple[Callable, FastAPI]] = None,
|
|
56
91
|
nacos_service: Optional[Callable] = None,
|
|
57
92
|
logging_service: Optional[Callable] = None,
|
|
58
93
|
database_service: Optional[Union[Tuple[Callable,
|
|
@@ -60,8 +95,10 @@ class Services(metaclass=SingletonMeta):
|
|
|
60
95
|
rabbitmq_listeners: Optional[List[RabbitMQListenerConfig]] = None,
|
|
61
96
|
rabbitmq_senders: Optional[List[RabbitMQSendConfig]] = None
|
|
62
97
|
) -> None:
|
|
63
|
-
"""
|
|
98
|
+
"""实例方法:实际执行各种服务插件的注册逻辑"""
|
|
64
99
|
# 注册非异步服务
|
|
100
|
+
if middleware:
|
|
101
|
+
self._setup_middleware(middleware)
|
|
65
102
|
if nacos_service:
|
|
66
103
|
nacos_service(self._config)
|
|
67
104
|
if logging_service:
|
|
@@ -69,6 +106,8 @@ class Services(metaclass=SingletonMeta):
|
|
|
69
106
|
if database_service:
|
|
70
107
|
self._setup_database(database_service)
|
|
71
108
|
|
|
109
|
+
RabbitMQService.init(self._config)
|
|
110
|
+
|
|
72
111
|
# MQ设置异步函数
|
|
73
112
|
async def setup_mq_components():
|
|
74
113
|
if rabbitmq_senders:
|
|
@@ -87,6 +126,11 @@ class Services(metaclass=SingletonMeta):
|
|
|
87
126
|
for db_setup, db_name in database_service:
|
|
88
127
|
db_setup(self._config, db_name)
|
|
89
128
|
|
|
129
|
+
def _setup_middleware(self, middleware):
|
|
130
|
+
if isinstance(middleware, tuple):
|
|
131
|
+
middleware_setup, app = middleware
|
|
132
|
+
middleware_setup(app, self._config)
|
|
133
|
+
|
|
90
134
|
def _setup_senders(self, rabbitmq_senders):
|
|
91
135
|
Services._registered_senders = [
|
|
92
136
|
sender.queue_name for sender in rabbitmq_senders]
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
sycommon/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
-
sycommon/services.py,sha256=
|
|
2
|
+
sycommon/services.py,sha256=Ow3BwiscQeX0k9fcr5t9ykpw6Oy-vcKkLR_UlFTb4WQ,8537
|
|
3
3
|
sycommon/config/Config.py,sha256=rSqr-6QIf4ISbfkGffqKhrZrSV4K_9QEXEmTPjnJ28c,3023
|
|
4
4
|
sycommon/config/DatabaseConfig.py,sha256=ILiUuYT9_xJZE2W-RYuC3JCt_YLKc1sbH13-MHIOPhg,804
|
|
5
5
|
sycommon/config/EmbeddingConfig.py,sha256=gPKwiDYbeu1GpdIZXMmgqM7JqBIzCXi0yYuGRLZooMI,362
|
|
@@ -19,12 +19,13 @@ sycommon/middleware/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSu
|
|
|
19
19
|
sycommon/middleware/context.py,sha256=_5ghpv4u_yAvjkgM-XDx8OnO-YI1XtntHrXsHJHZkwo,88
|
|
20
20
|
sycommon/middleware/cors.py,sha256=bGwDPI5Bfr0yH0hM-K7wK8mur5YqTy_XVZqlsdY_WdU,301
|
|
21
21
|
sycommon/middleware/exception.py,sha256=Bk8IchNND1wg6tUX9hf4xWeEJhvA-E_zE9ysBpRZrqE,3010
|
|
22
|
-
sycommon/middleware/middleware.py,sha256=
|
|
22
|
+
sycommon/middleware/middleware.py,sha256=z6osiDyKDxNKqErI29RVgijcjjl8e2wg-T9WN4xdbys,1220
|
|
23
23
|
sycommon/middleware/monitor_memory.py,sha256=pYRK-wRuDd6enSg9Pf8tQxPdYQS6S0AyjyXeKFRLKEs,628
|
|
24
24
|
sycommon/middleware/mq.py,sha256=4wBqiT5wJGcrfjk2GSr0_U3TStBxoNpHTzcRxVlMEHE,183
|
|
25
25
|
sycommon/middleware/timeout.py,sha256=fImlAPLm4Oa8N9goXtT_0os1GZPCi9F92OgXU81DgDU,656
|
|
26
26
|
sycommon/middleware/traceid.py,sha256=2QtyyOlSOB6QnGyZatevxUYyrzicbVD1ROA3KXn2SEo,5470
|
|
27
27
|
sycommon/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
28
|
+
sycommon/models/base_http.py,sha256=bbVvNnqi22DZavYKsYJN0Z1yJzfF9vzUzG_u2lFpNlc,2886
|
|
28
29
|
sycommon/models/log.py,sha256=rZpj6VkDRxK3B6H7XSeWdYZshU8F0Sks8bq1p6pPlDw,500
|
|
29
30
|
sycommon/models/mqlistener_config.py,sha256=PPwhAVJ2AWvVAvNox_1t0fuBKTyRH3Ui9cuuU-q7Byo,1590
|
|
30
31
|
sycommon/models/mqmsg_model.py,sha256=cxn0M5b0utQK6crMYmL-1waeGYHvK3AlGaRy23clqTE,277
|
|
@@ -38,7 +39,7 @@ sycommon/synacos/nacos_service.py,sha256=8l2qaVg5GQSTybGrcdmg0B5jRNAzbOPM3mjQ6T0
|
|
|
38
39
|
sycommon/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
39
40
|
sycommon/tools/snowflake.py,sha256=rc-VUjBMMpdAvbnHroVwfVt1xzApJbTCthUy9mglAuw,237
|
|
40
41
|
sycommon/tools/timing.py,sha256=OiiE7P07lRoMzX9kzb8sZU9cDb0zNnqIlY5pWqHcnkY,2064
|
|
41
|
-
sycommon_python_lib-0.1.
|
|
42
|
-
sycommon_python_lib-0.1.
|
|
43
|
-
sycommon_python_lib-0.1.
|
|
44
|
-
sycommon_python_lib-0.1.
|
|
42
|
+
sycommon_python_lib-0.1.3.dist-info/METADATA,sha256=gMk24-2tUlocvBYsQWJAbZeM_pg3opRbX7JnAtg25kc,7002
|
|
43
|
+
sycommon_python_lib-0.1.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
44
|
+
sycommon_python_lib-0.1.3.dist-info/top_level.txt,sha256=qb-vRf3lrmIaCLrGZxsv6k8Q8l3_lGuAeFtwjh0wYCQ,9
|
|
45
|
+
sycommon_python_lib-0.1.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|