swiftapi-kernel 0.1.0__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 swiftapi-kernel might be problematic. Click here for more details.
- swiftapi/__init__.py +22 -0
- swiftapi/app/__init__.py +0 -0
- swiftapi/app/factory.py +200 -0
- swiftapi/app/lifespan.py +167 -0
- swiftapi/app/routers.py +58 -0
- swiftapi/cli/__init__.py +0 -0
- swiftapi/cli/admin.py +198 -0
- swiftapi/cli/appref.py +51 -0
- swiftapi/cli/audit.py +45 -0
- swiftapi/cli/db.py +185 -0
- swiftapi/cli/endpoint.py +169 -0
- swiftapi/cli/logs.py +100 -0
- swiftapi/cli/main.py +238 -0
- swiftapi/cli/new.py +113 -0
- swiftapi/cli/openapi.py +69 -0
- swiftapi/cli/resource.py +657 -0
- swiftapi/cli/scaffold.py +168 -0
- swiftapi/config/__init__.py +0 -0
- swiftapi/config/constants.py +51 -0
- swiftapi/config/environments.py +38 -0
- swiftapi/config/settings.py +764 -0
- swiftapi/core/__init__.py +0 -0
- swiftapi/core/admin/__init__.py +0 -0
- swiftapi/core/admin/accounts.py +385 -0
- swiftapi/core/admin/audit.py +203 -0
- swiftapi/core/admin/maintenance.py +53 -0
- swiftapi/core/admin/registry.py +53 -0
- swiftapi/core/admin/security.py +94 -0
- swiftapi/core/admin/session.py +154 -0
- swiftapi/core/admin/views.py +2428 -0
- swiftapi/core/cache/__init__.py +0 -0
- swiftapi/core/cache/base.py +29 -0
- swiftapi/core/cache/decorators.py +51 -0
- swiftapi/core/cache/factory.py +30 -0
- swiftapi/core/cache/keys.py +24 -0
- swiftapi/core/cache/memory.py +60 -0
- swiftapi/core/cache/null.py +28 -0
- swiftapi/core/cache/redis.py +50 -0
- swiftapi/core/container.py +209 -0
- swiftapi/core/db/__init__.py +0 -0
- swiftapi/core/db/base_model.py +122 -0
- swiftapi/core/db/crud.py +242 -0
- swiftapi/core/db/dialects/__init__.py +8 -0
- swiftapi/core/db/dialects/base.py +106 -0
- swiftapi/core/db/dialects/mysql.py +47 -0
- swiftapi/core/db/dialects/pg.py +51 -0
- swiftapi/core/db/dialects/registry.py +30 -0
- swiftapi/core/db/dialects/sqlite.py +47 -0
- swiftapi/core/db/engine.py +209 -0
- swiftapi/core/db/health.py +84 -0
- swiftapi/core/db/migrate/__init__.py +1 -0
- swiftapi/core/db/migrate/ddl.py +162 -0
- swiftapi/core/db/migrate/render.py +84 -0
- swiftapi/core/db/migrate/runner.py +159 -0
- swiftapi/core/db/migrate/schema.py +248 -0
- swiftapi/core/db/mixins.py +53 -0
- swiftapi/core/db/session.py +54 -0
- swiftapi/core/db/snapshot.py +33 -0
- swiftapi/core/db/tenant_model.py +43 -0
- swiftapi/core/db/tenant_router.py +114 -0
- swiftapi/core/db/types.py +109 -0
- swiftapi/core/db/unit_of_work.py +65 -0
- swiftapi/core/docs/__init__.py +0 -0
- swiftapi/core/docs/router.py +26 -0
- swiftapi/core/docs/tsgen.py +93 -0
- swiftapi/core/docs/ui.py +132 -0
- swiftapi/core/errors/__init__.py +0 -0
- swiftapi/core/errors/base.py +168 -0
- swiftapi/core/errors/codes.py +117 -0
- swiftapi/core/errors/handlers.py +155 -0
- swiftapi/core/errors/problem.py +58 -0
- swiftapi/core/errors/validation.py +11 -0
- swiftapi/core/framework_models.py +22 -0
- swiftapi/core/http/__init__.py +47 -0
- swiftapi/core/http/app.py +247 -0
- swiftapi/core/http/cors.py +100 -0
- swiftapi/core/http/idempotency.py +148 -0
- swiftapi/core/http/middleware/__init__.py +82 -0
- swiftapi/core/http/middleware/access_log.py +57 -0
- swiftapi/core/http/middleware/auth.py +105 -0
- swiftapi/core/http/middleware/body_limit.py +76 -0
- swiftapi/core/http/middleware/rate_limit.py +103 -0
- swiftapi/core/http/middleware/request_body.py +122 -0
- swiftapi/core/http/middleware/request_id.py +46 -0
- swiftapi/core/http/middleware/security_headers.py +46 -0
- swiftapi/core/http/middleware/tenant.py +93 -0
- swiftapi/core/http/middleware/timing.py +57 -0
- swiftapi/core/http/multipart.py +116 -0
- swiftapi/core/http/multipart_stream.py +216 -0
- swiftapi/core/http/openapi.py +148 -0
- swiftapi/core/http/pagination.py +55 -0
- swiftapi/core/http/params.py +302 -0
- swiftapi/core/http/request.py +145 -0
- swiftapi/core/http/responses.py +127 -0
- swiftapi/core/http/routing.py +200 -0
- swiftapi/core/http/types.py +86 -0
- swiftapi/core/http/uploads.py +222 -0
- swiftapi/core/messaging/__init__.py +0 -0
- swiftapi/core/messaging/base.py +33 -0
- swiftapi/core/messaging/consumer.py +57 -0
- swiftapi/core/messaging/factory.py +30 -0
- swiftapi/core/messaging/idempotency.py +61 -0
- swiftapi/core/messaging/inprocess.py +30 -0
- swiftapi/core/messaging/outbox.py +106 -0
- swiftapi/core/messaging/rabbitmq.py +186 -0
- swiftapi/core/messaging/relay.py +151 -0
- swiftapi/core/messaging/streams.py +141 -0
- swiftapi/core/observability/__init__.py +0 -0
- swiftapi/core/observability/archive.py +136 -0
- swiftapi/core/observability/context.py +102 -0
- swiftapi/core/observability/logging.py +192 -0
- swiftapi/core/observability/masking.py +74 -0
- swiftapi/core/observability/metrics.py +101 -0
- swiftapi/core/observability/volume.py +67 -0
- swiftapi/core/resilience/__init__.py +0 -0
- swiftapi/core/resilience/bulkhead.py +50 -0
- swiftapi/core/resilience/circuit_breaker.py +97 -0
- swiftapi/core/resilience/client.py +179 -0
- swiftapi/core/resilience/retry.py +59 -0
- swiftapi/core/security/__init__.py +0 -0
- swiftapi/core/security/jwt.py +78 -0
- swiftapi/core/security/principal.py +78 -0
- swiftapi/core/tenant/__init__.py +1 -0
- swiftapi/core/tenant/catalog.py +89 -0
- swiftapi/core/tenant/context.py +75 -0
- swiftapi/core/tenant/isolation.py +48 -0
- swiftapi/core/tenant/resolver.py +48 -0
- swiftapi/core/validation/__init__.py +0 -0
- swiftapi/core/validation/base.py +32 -0
- swiftapi/db.py +50 -0
- swiftapi/modules/__init__.py +0 -0
- swiftapi/modules/users/__init__.py +11 -0
- swiftapi/modules/users/api/__init__.py +0 -0
- swiftapi/modules/users/api/users.py +110 -0
- swiftapi/modules/users/crud/__init__.py +0 -0
- swiftapi/modules/users/crud/user.py +23 -0
- swiftapi/modules/users/errors.py +24 -0
- swiftapi/modules/users/mappers.py +19 -0
- swiftapi/modules/users/model/__init__.py +0 -0
- swiftapi/modules/users/model/user.py +37 -0
- swiftapi/modules/users/policies.py +19 -0
- swiftapi/modules/users/schema/__init__.py +0 -0
- swiftapi/modules/users/schema/user.py +40 -0
- swiftapi/modules/users/service/__init__.py +0 -0
- swiftapi/modules/users/service/user.py +107 -0
- swiftapi/py.typed +0 -0
- swiftapi/templates/__init__.py +0 -0
- swiftapi/templates/app_skeleton/README.md +17 -0
- swiftapi/templates/app_skeleton/__init__.py +1 -0
- swiftapi/templates/app_skeleton/api/__init__.py +23 -0
- swiftapi/templates/app_skeleton/api/health.py +12 -0
- swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
- swiftapi/templates/app_skeleton/model/__init__.py +1 -0
- swiftapi/templates/app_skeleton/router.py +16 -0
- swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
- swiftapi/templates/app_skeleton/service/__init__.py +1 -0
- swiftapi/templates/project/__init__.py +0 -0
- swiftapi/templates/project/api.py +135 -0
- swiftapi/templates/project/app.py +57 -0
- swiftapi/templates/project/endpoints/__init__.py +25 -0
- swiftapi/templates/project/events.py +43 -0
- swiftapi/templates/project/models.py +79 -0
- swiftapi/templates/project/resources/__init__.py +35 -0
- swiftapi/templates/project/schemas.py +45 -0
- swiftapi/templates/project/service.py +125 -0
- swiftapi/templates/project/settings.py +17 -0
- swiftapi/templates/project_skeleton/.env.example +5 -0
- swiftapi/templates/project_skeleton/.gitignore +6 -0
- swiftapi/templates/project_skeleton/README.md +25 -0
- swiftapi/templates/project_skeleton/__init__.py +1 -0
- swiftapi/templates/project_skeleton/app.py +26 -0
- swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
- swiftapi/templates/project_skeleton/common/__init__.py +4 -0
- swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
- swiftapi/templates/project_skeleton/conf/settings.py +73 -0
- swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
- swiftapi/templates/project_skeleton/models.py +12 -0
- swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
- swiftapi/templates/project_skeleton/router.py +46 -0
- swiftapi/templates/project_skeleton/script/start.sh +13 -0
- swiftapi/templates/project_skeleton/start.py +35 -0
- swiftapi/version.py +8 -0
- swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
- swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
- swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
- swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
- swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""OpenAPI 3.1 生成:路由 + Pydantic 模型 → 契约文档。
|
|
2
|
+
|
|
3
|
+
为什么自研:契约要由我们决定(多租户头、错误码、`x-` 扩展、problem+json),
|
|
4
|
+
而不是在框架产物上打补丁。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import inspect
|
|
10
|
+
import re
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, TypeAdapter
|
|
14
|
+
|
|
15
|
+
from swiftapi.core.errors.problem import ProblemDetail
|
|
16
|
+
from swiftapi.core.http.routing import Route
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
19
|
+
from swiftapi.core.http.app import App
|
|
20
|
+
|
|
21
|
+
_REF = "#/components/schemas/{model}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def schema_name(model: type[BaseModel]) -> str:
|
|
25
|
+
"""泛型别名(Page[Item])不能直接作为 $ref 名字:清洗成 Page_Item_。"""
|
|
26
|
+
raw = getattr(model, "__name__", "Model")
|
|
27
|
+
return re.sub(r"[^A-Za-z0-9_]", "_", raw).strip("_") or "Model"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _register_schema(model: type[BaseModel], components: dict[str, Any]) -> dict[str, str]:
|
|
31
|
+
schema = model.model_json_schema(ref_template=_REF)
|
|
32
|
+
defs = schema.pop("$defs", {})
|
|
33
|
+
components["schemas"].update(defs)
|
|
34
|
+
name = schema_name(model)
|
|
35
|
+
components["schemas"][name] = schema
|
|
36
|
+
return {"$ref": _REF.format(model=name)}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _field_schema(annotation: Any, components: dict[str, Any]) -> dict[str, Any]:
|
|
40
|
+
if inspect.isclass(annotation) and issubclass(annotation, BaseModel):
|
|
41
|
+
return _register_schema(annotation, components)
|
|
42
|
+
try:
|
|
43
|
+
adapter: TypeAdapter[Any] = TypeAdapter(annotation)
|
|
44
|
+
return adapter.json_schema(ref_template=_REF)
|
|
45
|
+
except Exception: # 无法建模的注解退化为宽松对象
|
|
46
|
+
return {}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _parameters(route: Route, components: dict[str, Any]) -> list[dict[str, Any]]:
|
|
50
|
+
parameters: list[dict[str, Any]] = []
|
|
51
|
+
for binding in route.plan:
|
|
52
|
+
if binding.kind not in {"path", "query", "header"}:
|
|
53
|
+
continue
|
|
54
|
+
parameter: dict[str, Any] = {
|
|
55
|
+
"name": binding.alias,
|
|
56
|
+
"in": binding.kind,
|
|
57
|
+
"required": True if binding.kind == "path" else binding.required,
|
|
58
|
+
"schema": _field_schema(binding.annotation, components),
|
|
59
|
+
}
|
|
60
|
+
if binding.default is not None:
|
|
61
|
+
parameter["schema"] = {**parameter["schema"], "default": binding.default}
|
|
62
|
+
parameters.append(parameter)
|
|
63
|
+
return parameters
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _request_body(route: Route, components: dict[str, Any]) -> dict[str, Any] | None:
|
|
67
|
+
for binding in route.plan:
|
|
68
|
+
if binding.kind != "body":
|
|
69
|
+
continue
|
|
70
|
+
return {
|
|
71
|
+
"required": True,
|
|
72
|
+
"content": {"application/json": {"schema": _field_schema(binding.annotation, components)}},
|
|
73
|
+
}
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _problem_response(components: dict[str, Any], description: str) -> dict[str, Any]:
|
|
78
|
+
return {
|
|
79
|
+
"description": description,
|
|
80
|
+
"content": {"application/problem+json": {"schema": _register_schema(ProblemDetail, components)}},
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _operation(route: Route, components: dict[str, Any], operation_ids: set[str]) -> dict[str, Any]:
|
|
85
|
+
operation: dict[str, Any] = {
|
|
86
|
+
"operationId": _unique_operation_id(route, operation_ids),
|
|
87
|
+
"summary": route.summary or route.name,
|
|
88
|
+
"responses": {
|
|
89
|
+
str(route.status_code): {
|
|
90
|
+
"description": "Successful Response",
|
|
91
|
+
"content": {
|
|
92
|
+
"application/json": {
|
|
93
|
+
"schema": _field_schema(
|
|
94
|
+
route.response_model if route.response_model else Any,
|
|
95
|
+
components,
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
"422": _problem_response(components, "Request validation failed"),
|
|
101
|
+
"500": _problem_response(components, "Internal server error"),
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
if route.description:
|
|
105
|
+
operation["description"] = route.description
|
|
106
|
+
if route.tags:
|
|
107
|
+
operation["tags"] = list(route.tags)
|
|
108
|
+
parameters = _parameters(route, components)
|
|
109
|
+
if parameters:
|
|
110
|
+
operation["parameters"] = parameters
|
|
111
|
+
body = _request_body(route, components)
|
|
112
|
+
if body is not None:
|
|
113
|
+
operation["requestBody"] = body
|
|
114
|
+
return operation
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _unique_operation_id(route: Route, taken: set[str]) -> str:
|
|
118
|
+
"""OpenAPI 要求 operationId 全局唯一;按 tag 前缀 + 冲突计数去重。"""
|
|
119
|
+
base = f"{route.tags[0]}.{route.name}" if route.tags else route.name
|
|
120
|
+
candidate = base
|
|
121
|
+
index = 2
|
|
122
|
+
while candidate in taken:
|
|
123
|
+
candidate = f"{base}_{index}"
|
|
124
|
+
index += 1
|
|
125
|
+
taken.add(candidate)
|
|
126
|
+
return candidate
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def build_openapi(app: App) -> dict[str, Any]:
|
|
130
|
+
components: dict[str, Any] = {"schemas": {}}
|
|
131
|
+
paths: dict[str, dict[str, Any]] = {}
|
|
132
|
+
operation_ids: set[str] = set()
|
|
133
|
+
for route in app.router.routes:
|
|
134
|
+
if not route.include_in_schema:
|
|
135
|
+
continue
|
|
136
|
+
entry = paths.setdefault(route.path, {})
|
|
137
|
+
for method in sorted(route.methods):
|
|
138
|
+
entry[method.lower()] = _operation(route, components, operation_ids)
|
|
139
|
+
return {
|
|
140
|
+
"openapi": "3.1.0",
|
|
141
|
+
"info": {
|
|
142
|
+
"title": app.title,
|
|
143
|
+
"version": app.version,
|
|
144
|
+
"description": app.description,
|
|
145
|
+
},
|
|
146
|
+
"paths": paths,
|
|
147
|
+
"components": components,
|
|
148
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""分页契约:`Page[T]` 泛型 + 参数校验(架构文档 §14.1)。
|
|
2
|
+
|
|
3
|
+
offset 分页用于前 10 万行;更深的翻页由游标分页承担(P3 提供)。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
from swiftapi.core.validation.base import StrictModel
|
|
13
|
+
|
|
14
|
+
DEFAULT_LIMIT = 20
|
|
15
|
+
MAX_LIMIT = 100
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PageParams(StrictModel):
|
|
19
|
+
limit: int = Field(default=DEFAULT_LIMIT, ge=1, le=MAX_LIMIT)
|
|
20
|
+
offset: int = Field(default=0, ge=0)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Page[ItemT](StrictModel):
|
|
24
|
+
items: list[ItemT]
|
|
25
|
+
total: int = Field(ge=0)
|
|
26
|
+
limit: int = Field(ge=1)
|
|
27
|
+
offset: int = Field(ge=0)
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def has_next(self) -> bool:
|
|
31
|
+
return self.offset + len(self.items) < self.total
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def build(cls, items: list[ItemT], total: int, *, limit: int, offset: int) -> Page[ItemT]:
|
|
35
|
+
return cls(items=items, total=total, limit=limit, offset=offset)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def to_page[ItemT: BaseModel](
|
|
39
|
+
rows: Sequence[object],
|
|
40
|
+
total: int,
|
|
41
|
+
*,
|
|
42
|
+
limit: int,
|
|
43
|
+
offset: int,
|
|
44
|
+
schema: type[ItemT],
|
|
45
|
+
) -> Page[ItemT]:
|
|
46
|
+
"""ORM 行 → `Page[Out]`:省掉每个列表接口手写 dict 的样板。"""
|
|
47
|
+
return Page.build(
|
|
48
|
+
[schema.model_validate(row) for row in rows],
|
|
49
|
+
total,
|
|
50
|
+
limit=limit,
|
|
51
|
+
offset=offset,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
__all__ = ["DEFAULT_LIMIT", "MAX_LIMIT", "Page", "PageParams", "to_page"]
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""参数绑定:把 HTTP 输入变成已校验的 Python 对象。
|
|
2
|
+
|
|
3
|
+
四种来源 + 两种组合:
|
|
4
|
+
|
|
5
|
+
async def handler(
|
|
6
|
+
request: Request, # 显式注入
|
|
7
|
+
user_id: UUID = Path(), # 路径参数
|
|
8
|
+
limit: int = Query(20), # 查询参数
|
|
9
|
+
authorization: str = Header(), # 请求头
|
|
10
|
+
payload: UserCreate = Body(), # 请求体(Pydantic 校验)
|
|
11
|
+
principal: Principal = Depends(current_user), # 依赖
|
|
12
|
+
) -> ...: ...
|
|
13
|
+
|
|
14
|
+
设计取舍:不做"魔法注解"(如 `Annotated[T, Query()]` 的复杂组合),
|
|
15
|
+
显式 marker 更容易被静态检查与文档生成理解。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import inspect
|
|
21
|
+
from collections.abc import Awaitable, Callable
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from typing import Annotated, Any, get_args, get_origin, get_type_hints
|
|
24
|
+
|
|
25
|
+
from pydantic import BaseModel, TypeAdapter, ValidationError
|
|
26
|
+
|
|
27
|
+
from swiftapi.core.container import ContainerError
|
|
28
|
+
from swiftapi.core.errors.problem import FieldError
|
|
29
|
+
from swiftapi.core.errors.validation import RequestValidationError
|
|
30
|
+
from swiftapi.core.http.request import Request
|
|
31
|
+
|
|
32
|
+
_UNSET: Any = object()
|
|
33
|
+
_ADAPTER_CACHE: dict[Any, TypeAdapter[Any]] = {}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _adapter(annotation: Any) -> TypeAdapter[Any]:
|
|
37
|
+
adapter = _ADAPTER_CACHE.get(annotation)
|
|
38
|
+
if adapter is None:
|
|
39
|
+
adapter = TypeAdapter(annotation)
|
|
40
|
+
_ADAPTER_CACHE[annotation] = adapter
|
|
41
|
+
return adapter
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Marker:
|
|
45
|
+
"""参数来源标记。"""
|
|
46
|
+
|
|
47
|
+
kind: str = "query"
|
|
48
|
+
|
|
49
|
+
def __init__(self, default: Any = _UNSET, *, alias: str | None = None) -> None:
|
|
50
|
+
self.default = default
|
|
51
|
+
self.alias = alias
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def required(self) -> bool:
|
|
55
|
+
return self.default is _UNSET
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Path(Marker):
|
|
59
|
+
kind = "path"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Query(Marker):
|
|
63
|
+
kind = "query"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Header(Marker):
|
|
67
|
+
kind = "header"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Body(Marker):
|
|
71
|
+
kind = "body"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Depends:
|
|
75
|
+
"""依赖:从容器解析(推荐)或直接调用一个函数。
|
|
76
|
+
|
|
77
|
+
service: UserService = Depends("user_service") # 容器 key,支持请求作用域
|
|
78
|
+
principal: Principal = Depends(current_principal) # 纯函数,无状态
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def __init__(self, dependency: str | Callable[..., Any]) -> None:
|
|
82
|
+
self.key: str | None = dependency if isinstance(dependency, str) else None
|
|
83
|
+
self.dependency: Callable[..., Any] | None = (
|
|
84
|
+
None if isinstance(dependency, str) else dependency
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class Binding:
|
|
90
|
+
name: str
|
|
91
|
+
kind: str # request / path / query / header / body / depends
|
|
92
|
+
alias: str
|
|
93
|
+
required: bool
|
|
94
|
+
annotation: Any
|
|
95
|
+
default: Any = None
|
|
96
|
+
is_model: bool = False
|
|
97
|
+
dependency: Callable[..., Any] | None = None
|
|
98
|
+
key: str | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _is_model(annotation: Any) -> bool:
|
|
102
|
+
return inspect.isclass(annotation) and issubclass(annotation, BaseModel)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def build_plan(handler: Callable[..., Any]) -> list[Binding]:
|
|
106
|
+
"""在注册期解析签名,运行期不再做反射。"""
|
|
107
|
+
try:
|
|
108
|
+
hints = get_type_hints(handler, include_extras=True)
|
|
109
|
+
except Exception: # 注解无法解析时退回原始注解,不让注册期崩溃
|
|
110
|
+
hints = {}
|
|
111
|
+
bindings: list[Binding] = []
|
|
112
|
+
for name, parameter in inspect.signature(handler).parameters.items():
|
|
113
|
+
if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):
|
|
114
|
+
raise TypeError(f"{handler.__name__} 不接受 *args/**kwargs 参数")
|
|
115
|
+
annotation = hints.get(name, parameter.annotation)
|
|
116
|
+
default = parameter.default
|
|
117
|
+
|
|
118
|
+
# 支持 Annotated[T, Depends("key")] / Annotated[T, Query()]
|
|
119
|
+
metadata: tuple[Any, ...] = ()
|
|
120
|
+
if get_origin(annotation) is Annotated:
|
|
121
|
+
base, *metadata_items = get_args(annotation)
|
|
122
|
+
metadata = tuple(metadata_items)
|
|
123
|
+
annotation = base
|
|
124
|
+
|
|
125
|
+
annotated_depends = next((item for item in metadata if isinstance(item, Depends)), None)
|
|
126
|
+
annotated_marker = next((item for item in metadata if isinstance(item, Marker)), None)
|
|
127
|
+
|
|
128
|
+
if annotated_depends is not None:
|
|
129
|
+
bindings.append(
|
|
130
|
+
Binding(
|
|
131
|
+
name=name,
|
|
132
|
+
kind="depends",
|
|
133
|
+
alias=name,
|
|
134
|
+
required=True,
|
|
135
|
+
annotation=Any,
|
|
136
|
+
dependency=annotated_depends.dependency,
|
|
137
|
+
key=annotated_depends.key,
|
|
138
|
+
)
|
|
139
|
+
)
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
if isinstance(default, Depends):
|
|
143
|
+
bindings.append(
|
|
144
|
+
Binding(
|
|
145
|
+
name=name,
|
|
146
|
+
kind="depends",
|
|
147
|
+
alias=name,
|
|
148
|
+
required=True,
|
|
149
|
+
annotation=Any,
|
|
150
|
+
dependency=default.dependency,
|
|
151
|
+
key=default.key,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
continue
|
|
155
|
+
|
|
156
|
+
if annotation is Request:
|
|
157
|
+
bindings.append(Binding(name=name, kind="request", alias=name, required=True, annotation=Request))
|
|
158
|
+
continue
|
|
159
|
+
|
|
160
|
+
marker = annotated_marker or (default if isinstance(default, Marker) else None)
|
|
161
|
+
kind = marker.kind if marker else None
|
|
162
|
+
alias = (marker.alias if marker else None) or name
|
|
163
|
+
|
|
164
|
+
if kind is None:
|
|
165
|
+
if _is_model(annotation) or annotation in {dict, list}:
|
|
166
|
+
kind = "body"
|
|
167
|
+
elif default is inspect.Parameter.empty:
|
|
168
|
+
kind = "query"
|
|
169
|
+
else:
|
|
170
|
+
kind = "query"
|
|
171
|
+
|
|
172
|
+
# 标记无默认值、但 Python 形参有默认值时,视为可选(依形参默认值)
|
|
173
|
+
required = marker.required and default is inspect.Parameter.empty if marker else default is inspect.Parameter.empty
|
|
174
|
+
default_value = None if (marker and marker.required) or default is inspect.Parameter.empty else (
|
|
175
|
+
marker.default if marker and marker.default is not _UNSET else default
|
|
176
|
+
)
|
|
177
|
+
bindings.append(
|
|
178
|
+
Binding(
|
|
179
|
+
name=name,
|
|
180
|
+
kind=kind,
|
|
181
|
+
alias=alias,
|
|
182
|
+
required=required,
|
|
183
|
+
annotation=annotation,
|
|
184
|
+
default=default_value,
|
|
185
|
+
is_model=_is_model(annotation),
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
return bindings
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
async def _resolve_dependency(
|
|
192
|
+
binding: Binding,
|
|
193
|
+
request: Request,
|
|
194
|
+
container: Any,
|
|
195
|
+
request_scope: Any,
|
|
196
|
+
) -> Any:
|
|
197
|
+
if binding.key is not None:
|
|
198
|
+
if container is None or request_scope is None:
|
|
199
|
+
raise ContainerError(
|
|
200
|
+
f'Depends("{binding.key}") 需要容器,但当前 App 未挂载 container'
|
|
201
|
+
)
|
|
202
|
+
return await container.resolve(binding.key, request_scope)
|
|
203
|
+
assert binding.dependency is not None
|
|
204
|
+
return await _call_dependency(binding.dependency, request)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
async def _call_dependency(dependency: Callable[..., Any], request: Request) -> Any:
|
|
208
|
+
result = dependency(request)
|
|
209
|
+
if inspect.isawaitable(result):
|
|
210
|
+
return await result
|
|
211
|
+
return result
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
async def _parse_model(raw: Any, annotation: Any, location: str) -> Any:
|
|
215
|
+
adapter = _adapter(annotation)
|
|
216
|
+
try:
|
|
217
|
+
return adapter.validate_python(raw)
|
|
218
|
+
except ValidationError as exc:
|
|
219
|
+
raise RequestValidationError(
|
|
220
|
+
[
|
|
221
|
+
FieldError(loc=[location, *map(str, error.get("loc", ()))], msg=str(error.get("msg")), type=str(error.get("type")))
|
|
222
|
+
for error in exc.errors()
|
|
223
|
+
]
|
|
224
|
+
) from exc
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
async def resolve(
|
|
228
|
+
plan: list[Binding],
|
|
229
|
+
request: Request,
|
|
230
|
+
*,
|
|
231
|
+
container: Any = None,
|
|
232
|
+
request_scope: Any = None,
|
|
233
|
+
) -> dict[str, Any]:
|
|
234
|
+
"""按 plan 绑定参数;任一失败抛 RequestValidationError(422)。"""
|
|
235
|
+
kwargs: dict[str, Any] = {}
|
|
236
|
+
errors: list[FieldError] = []
|
|
237
|
+
|
|
238
|
+
for binding in plan:
|
|
239
|
+
if binding.kind == "request":
|
|
240
|
+
kwargs[binding.name] = request
|
|
241
|
+
continue
|
|
242
|
+
if binding.kind == "depends":
|
|
243
|
+
kwargs[binding.name] = await _resolve_dependency(binding, request, container, request_scope)
|
|
244
|
+
continue
|
|
245
|
+
if binding.kind == "body":
|
|
246
|
+
raw_body = await request.json()
|
|
247
|
+
try:
|
|
248
|
+
kwargs[binding.name] = await _parse_model(raw_body, binding.annotation, "body")
|
|
249
|
+
except RequestValidationError as exc:
|
|
250
|
+
errors.extend(exc.errors)
|
|
251
|
+
continue
|
|
252
|
+
|
|
253
|
+
raw: str | None
|
|
254
|
+
if binding.kind == "path":
|
|
255
|
+
raw = request.path_params.get(binding.alias)
|
|
256
|
+
elif binding.kind == "header":
|
|
257
|
+
raw = request.headers.get(binding.alias)
|
|
258
|
+
else:
|
|
259
|
+
raw = request.query_params.get(binding.alias)
|
|
260
|
+
|
|
261
|
+
if raw is None or raw == "":
|
|
262
|
+
if binding.required:
|
|
263
|
+
errors.append(
|
|
264
|
+
FieldError(
|
|
265
|
+
loc=[binding.kind, binding.alias],
|
|
266
|
+
msg="Field required",
|
|
267
|
+
type="missing",
|
|
268
|
+
)
|
|
269
|
+
)
|
|
270
|
+
else:
|
|
271
|
+
kwargs[binding.name] = binding.default
|
|
272
|
+
continue
|
|
273
|
+
|
|
274
|
+
adapter = _adapter(binding.annotation)
|
|
275
|
+
try:
|
|
276
|
+
kwargs[binding.name] = adapter.validate_python(raw)
|
|
277
|
+
except ValidationError as exc:
|
|
278
|
+
errors.extend(
|
|
279
|
+
FieldError(
|
|
280
|
+
loc=[binding.kind, binding.alias, *map(str, error.get("loc", ()))],
|
|
281
|
+
msg=str(error.get("msg")),
|
|
282
|
+
type=str(error.get("type")),
|
|
283
|
+
)
|
|
284
|
+
for error in exc.errors()
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
if errors:
|
|
288
|
+
raise RequestValidationError(errors)
|
|
289
|
+
return kwargs
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
Dependency = Callable[[Request], Awaitable[Any] | Any]
|
|
293
|
+
__all__ = [
|
|
294
|
+
"Binding",
|
|
295
|
+
"Body",
|
|
296
|
+
"Depends",
|
|
297
|
+
"Header",
|
|
298
|
+
"Path",
|
|
299
|
+
"Query",
|
|
300
|
+
"build_plan",
|
|
301
|
+
"resolve",
|
|
302
|
+
]
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""请求对象:只暴露业务真正需要的视图(headers / query / path / body / client)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import parse_qsl, unquote
|
|
8
|
+
|
|
9
|
+
import orjson
|
|
10
|
+
|
|
11
|
+
from swiftapi.core.errors.base import PayloadTooLarge
|
|
12
|
+
from swiftapi.core.errors.problem import FieldError
|
|
13
|
+
from swiftapi.core.errors.validation import RequestValidationError
|
|
14
|
+
from swiftapi.core.http.types import Headers, Message, Receive, Scope
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Request:
|
|
18
|
+
__slots__ = ("_body", "_headers", "_query", "_receive", "path_params", "scope", "state")
|
|
19
|
+
|
|
20
|
+
def __init__(self, scope: Scope, receive: Receive) -> None:
|
|
21
|
+
self.scope = scope
|
|
22
|
+
self._receive = receive
|
|
23
|
+
self._body: bytes | None = None
|
|
24
|
+
self._headers: Headers | None = None
|
|
25
|
+
self._query: dict[str, str] | None = None
|
|
26
|
+
self.state: dict[str, Any] = scope.setdefault("state", {})
|
|
27
|
+
self.path_params: dict[str, str] = {}
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def method(self) -> str:
|
|
31
|
+
return str(self.scope.get("method", "GET")).upper()
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def path(self) -> str:
|
|
35
|
+
return unquote(str(self.scope.get("path", "/")))
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def http_version(self) -> str:
|
|
39
|
+
return str(self.scope.get("http_version", "1.1"))
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def headers(self) -> Headers:
|
|
43
|
+
if self._headers is None:
|
|
44
|
+
self._headers = Headers.from_scope(self.scope)
|
|
45
|
+
return self._headers
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def client(self) -> tuple[str, int] | None:
|
|
49
|
+
client = self.scope.get("client")
|
|
50
|
+
return (str(client[0]), int(client[1])) if client else None
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def cookies(self) -> dict[str, str]:
|
|
54
|
+
"""解析 `Cookie` 头(后台会话用;同名取最后一个,与浏览器行为一致)。"""
|
|
55
|
+
raw = self.headers.get("cookie") or ""
|
|
56
|
+
jar: dict[str, str] = {}
|
|
57
|
+
for part in raw.split(";"):
|
|
58
|
+
name, separator, value = part.strip().partition("=")
|
|
59
|
+
if separator and name:
|
|
60
|
+
jar[name.strip()] = value.strip()
|
|
61
|
+
return jar
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def query_string(self) -> str:
|
|
65
|
+
raw = self.scope.get("query_string", b"")
|
|
66
|
+
return raw.decode("latin-1") if isinstance(raw, bytes) else str(raw)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def query_params(self) -> dict[str, str]:
|
|
70
|
+
"""同名参数取第一个值(多值场景用 `query_params_multi`)。结果按请求缓存。"""
|
|
71
|
+
if self._query is None:
|
|
72
|
+
self._query = dict(parse_qsl(self.query_string, keep_blank_values=True))
|
|
73
|
+
return self._query
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def query_params_multi(self) -> dict[str, list[str]]:
|
|
77
|
+
multi: dict[str, list[str]] = {}
|
|
78
|
+
for key, value in parse_qsl(self.query_string, keep_blank_values=True):
|
|
79
|
+
multi.setdefault(key, []).append(value)
|
|
80
|
+
return multi
|
|
81
|
+
|
|
82
|
+
async def body(self) -> bytes:
|
|
83
|
+
if self._body is None:
|
|
84
|
+
chunks: list[bytes] = []
|
|
85
|
+
while True:
|
|
86
|
+
message: Message = await self._receive()
|
|
87
|
+
if message["type"] != "http.request":
|
|
88
|
+
break
|
|
89
|
+
chunks.append(bytes(message.get("body", b"")))
|
|
90
|
+
if not message.get("more_body", False):
|
|
91
|
+
break
|
|
92
|
+
self._body = b"".join(chunks)
|
|
93
|
+
return self._body
|
|
94
|
+
|
|
95
|
+
async def iter_chunks(self, *, max_bytes: int | None = None) -> AsyncIterator[bytes]:
|
|
96
|
+
"""按到达顺序吐 chunk,不整体缓冲(大文件上传用)。
|
|
97
|
+
|
|
98
|
+
`max_bytes` 超限立即抛 413 —— 调用方负责清理已写入的临时文件。
|
|
99
|
+
如果 body 已被读过(`body()`),退化为一次性返回缓存。
|
|
100
|
+
"""
|
|
101
|
+
if self._body is not None:
|
|
102
|
+
if self._body:
|
|
103
|
+
yield self._body
|
|
104
|
+
return
|
|
105
|
+
|
|
106
|
+
total = 0
|
|
107
|
+
while True:
|
|
108
|
+
message: Message = await self._receive()
|
|
109
|
+
if message["type"] != "http.request":
|
|
110
|
+
break
|
|
111
|
+
chunk = bytes(message.get("body", b""))
|
|
112
|
+
if chunk:
|
|
113
|
+
total += len(chunk)
|
|
114
|
+
if max_bytes is not None and total > max_bytes:
|
|
115
|
+
raise PayloadTooLarge(f"请求体超过上限 {max_bytes} 字节")
|
|
116
|
+
yield chunk
|
|
117
|
+
if not message.get("more_body", False):
|
|
118
|
+
break
|
|
119
|
+
|
|
120
|
+
async def form(self) -> dict[str, str]:
|
|
121
|
+
"""解析 `application/x-www-form-urlencoded`(管理后台表单用)。"""
|
|
122
|
+
raw = await self.body()
|
|
123
|
+
parsed = parse_qsl(raw.decode("utf-8"), keep_blank_values=True)
|
|
124
|
+
return {key: value for key, value in parsed}
|
|
125
|
+
|
|
126
|
+
async def form_multi(self) -> dict[str, list[str]]:
|
|
127
|
+
"""保留重复键(批量操作的 `ids` 会用多次)。"""
|
|
128
|
+
raw = await self.body()
|
|
129
|
+
multi: dict[str, list[str]] = {}
|
|
130
|
+
for key, value in parse_qsl(raw.decode("utf-8"), keep_blank_values=True):
|
|
131
|
+
multi.setdefault(key, []).append(value)
|
|
132
|
+
return multi
|
|
133
|
+
|
|
134
|
+
async def json(self) -> Any:
|
|
135
|
+
raw = await self.body()
|
|
136
|
+
if not raw:
|
|
137
|
+
raise RequestValidationError(
|
|
138
|
+
[FieldError(loc=["body"], msg="Request body is required", type="missing")]
|
|
139
|
+
)
|
|
140
|
+
try:
|
|
141
|
+
return orjson.loads(raw)
|
|
142
|
+
except orjson.JSONDecodeError as exc:
|
|
143
|
+
raise RequestValidationError(
|
|
144
|
+
[FieldError(loc=["body"], msg=f"Invalid JSON: {exc}", type="json_invalid")]
|
|
145
|
+
) from exc
|