done-coding-schema-api 0.0.1a0__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.
@@ -0,0 +1,64 @@
1
+ """跨前后端通用接口结构的 Pydantic 模型与常量。
2
+
3
+ 模型与常量由仓根 ``schemas/`` 的 JSON Schema 定义生成;成功外壳、三种列表、错误体、
4
+ 筛选参数与专有码清单以 ``models`` 里的包装版本导出(带泛型与生成工具表达不了的约束)。
5
+ """
6
+
7
+ from ._generated.constants import (
8
+ BOUNDED_LIST_RESPONSE_PATHS,
9
+ COMMON_ERROR_CODE_TABLE,
10
+ COMMON_ERROR_CODES,
11
+ CURSOR_LIST_REQUEST_PARAMS,
12
+ CURSOR_LIST_RESPONSE_PATHS,
13
+ LIST_FILTER_PARAMS,
14
+ PAGED_LIST_REQUEST_PARAMS,
15
+ PAGED_LIST_RESPONSE_PATHS,
16
+ SUCCESS_CODES,
17
+ CommonErrorCode,
18
+ SuccessCode,
19
+ )
20
+ from ._generated.cursor_list import CursorListCursor
21
+ from ._generated.cursor_list_request import CursorListRequest
22
+ from ._generated.error_body import ErrorDetail, ErrorField
23
+ from ._generated.list_filter import ListFilterCondition
24
+ from ._generated.paged_list import PagedListPage
25
+ from ._generated.paged_list_request import PagedListRequest
26
+ from ._generated.service_error_codes import ServiceErrorCode
27
+ from .models import (
28
+ BoundedList,
29
+ CursorList,
30
+ ErrorBody,
31
+ ListFilter,
32
+ PagedList,
33
+ ServiceErrorCodes,
34
+ SuccessEnvelope,
35
+ )
36
+
37
+ __all__ = [
38
+ "BOUNDED_LIST_RESPONSE_PATHS",
39
+ "COMMON_ERROR_CODES",
40
+ "COMMON_ERROR_CODE_TABLE",
41
+ "CURSOR_LIST_REQUEST_PARAMS",
42
+ "CURSOR_LIST_RESPONSE_PATHS",
43
+ "LIST_FILTER_PARAMS",
44
+ "PAGED_LIST_REQUEST_PARAMS",
45
+ "PAGED_LIST_RESPONSE_PATHS",
46
+ "SUCCESS_CODES",
47
+ "BoundedList",
48
+ "CommonErrorCode",
49
+ "CursorList",
50
+ "CursorListCursor",
51
+ "CursorListRequest",
52
+ "ErrorBody",
53
+ "ErrorDetail",
54
+ "ErrorField",
55
+ "ListFilter",
56
+ "ListFilterCondition",
57
+ "PagedList",
58
+ "PagedListPage",
59
+ "PagedListRequest",
60
+ "ServiceErrorCode",
61
+ "ServiceErrorCodes",
62
+ "SuccessCode",
63
+ "SuccessEnvelope",
64
+ ]
@@ -0,0 +1,40 @@
1
+ """生成模型的基类(手写,生成器以 --base-class 引用)。"""
2
+
3
+ from typing import Any
4
+
5
+ from pydantic import BaseModel, ConfigDict, model_validator
6
+
7
+
8
+ class SchemaModel(BaseModel):
9
+ """所有生成模型的基类。
10
+
11
+ - strict:不做 "10" → 10、"true" → True 这类类型转换,与定义的类型约束一致;
12
+ - extra="allow":定义里未声明 additionalProperties 的对象(三种列表的顶层)
13
+ 保留接口自己声明的附带字段;声明了 additionalProperties: false 的模型由生成的
14
+ model_config 覆盖为 forbid;
15
+ - serialize_by_alias / validate_by_name:输出用线上字段名(如 ErrorField 的 in),
16
+ Python 里也可以用字段名(in_)构造。
17
+ """
18
+
19
+ model_config = ConfigDict(
20
+ strict=True,
21
+ extra="allow",
22
+ serialize_by_alias=True,
23
+ validate_by_name=True,
24
+ )
25
+
26
+ @model_validator(mode="before")
27
+ @classmethod
28
+ def _reject_null_for_optional(cls, data: Any) -> Any:
29
+ """可选字段在定义里都不可为 null:不需要时省略,不接受显式 null。
30
+
31
+ 生成工具把可选字段写成 `X | None = None`,会放过显式 null;这里补上。
32
+ """
33
+ if isinstance(data, dict):
34
+ for name, field in cls.model_fields.items():
35
+ if field.is_required():
36
+ continue
37
+ for key in {name, field.alias or name}:
38
+ if key in data and data[key] is None:
39
+ raise ValueError(f"{key} 不能为 null;不需要时省略该字段")
40
+ return data
@@ -0,0 +1,4 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: in
@@ -0,0 +1,19 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: bounded-list.json
5
+
6
+ from __future__ import annotations
7
+ from typing import Any
8
+ from done_coding_schema_api._base import SchemaModel
9
+
10
+
11
+ class BoundedList(SchemaModel):
12
+ """
13
+ 一次性列表,作成功外壳的 data。只用于条数有一个由定义决定、不随业务数据增长的上限的结果(如下拉选项);上限由各接口在自己的契约里声明,超过上限报 LIST_LIMIT_EXCEEDED,不截断。顶层允许接口自己声明的附带字段,但不得带翻页信息。
14
+ """
15
+
16
+ items: list[Any]
17
+ """
18
+ 列表数据。
19
+ """
@@ -0,0 +1,172 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ from types import MappingProxyType
4
+ from typing import Final, Literal
5
+
6
+
7
+ SUCCESS_CODES: Final = MappingProxyType({"OK": "OK"})
8
+ """成功码。成功外壳的 code 只能是这一组里的值。"""
9
+ SuccessCode = Literal["OK"]
10
+
11
+ COMMON_ERROR_CODES: Final = MappingProxyType(
12
+ {
13
+ "INVALID_REQUEST": "INVALID_REQUEST",
14
+ "UNAUTHENTICATED": "UNAUTHENTICATED",
15
+ "FORBIDDEN": "FORBIDDEN",
16
+ "NOT_FOUND": "NOT_FOUND",
17
+ "ROUTE_NOT_FOUND": "ROUTE_NOT_FOUND",
18
+ "METHOD_NOT_ALLOWED": "METHOD_NOT_ALLOWED",
19
+ "CONFLICT": "CONFLICT",
20
+ "RATE_LIMITED": "RATE_LIMITED",
21
+ "INTERNAL_ERROR": "INTERNAL_ERROR",
22
+ "LIST_LIMIT_EXCEEDED": "LIST_LIMIT_EXCEEDED",
23
+ "SERVICE_UNAVAILABLE": "SERVICE_UNAVAILABLE",
24
+ }
25
+ )
26
+ """通用失败码。错误体的 code 是开放字符串,这里只列通用的一组;
27
+ 各服务可以有自己的专有码,遇到不认识的码按 HTTP 状态归类处理。"""
28
+ CommonErrorCode = Literal[
29
+ "INVALID_REQUEST",
30
+ "UNAUTHENTICATED",
31
+ "FORBIDDEN",
32
+ "NOT_FOUND",
33
+ "ROUTE_NOT_FOUND",
34
+ "METHOD_NOT_ALLOWED",
35
+ "CONFLICT",
36
+ "RATE_LIMITED",
37
+ "INTERNAL_ERROR",
38
+ "LIST_LIMIT_EXCEEDED",
39
+ "SERVICE_UNAVAILABLE",
40
+ ]
41
+
42
+ COMMON_ERROR_CODE_TABLE: Final = MappingProxyType(
43
+ {
44
+ "INVALID_REQUEST": MappingProxyType(
45
+ {
46
+ "httpStatus": 400,
47
+ "retryable": False,
48
+ "outcome": "not_executed",
49
+ "meaning": "请求不符合接口契约",
50
+ }
51
+ ),
52
+ "UNAUTHENTICATED": MappingProxyType(
53
+ {
54
+ "httpStatus": 401,
55
+ "retryable": False,
56
+ "outcome": "not_executed",
57
+ "meaning": "未登录,或令牌无效、过期",
58
+ }
59
+ ),
60
+ "FORBIDDEN": MappingProxyType(
61
+ {
62
+ "httpStatus": 403,
63
+ "retryable": False,
64
+ "outcome": "not_executed",
65
+ "meaning": "已认证但无权执行",
66
+ }
67
+ ),
68
+ "NOT_FOUND": MappingProxyType(
69
+ {
70
+ "httpStatus": 404,
71
+ "retryable": False,
72
+ "outcome": "not_executed",
73
+ "meaning": "资源不存在,或调用方无权得知其存在",
74
+ }
75
+ ),
76
+ "ROUTE_NOT_FOUND": MappingProxyType(
77
+ {
78
+ "httpStatus": 404,
79
+ "retryable": False,
80
+ "outcome": "not_executed",
81
+ "meaning": "接口路径不存在",
82
+ }
83
+ ),
84
+ "METHOD_NOT_ALLOWED": MappingProxyType(
85
+ {
86
+ "httpStatus": 405,
87
+ "retryable": False,
88
+ "outcome": "not_executed",
89
+ "meaning": "接口不支持该 HTTP 方法",
90
+ }
91
+ ),
92
+ "CONFLICT": MappingProxyType(
93
+ {
94
+ "httpStatus": 409,
95
+ "retryable": False,
96
+ "outcome": "not_executed",
97
+ "meaning": "资源状态冲突",
98
+ }
99
+ ),
100
+ "RATE_LIMITED": MappingProxyType(
101
+ {
102
+ "httpStatus": 429,
103
+ "retryable": True,
104
+ "outcome": "not_executed",
105
+ "meaning": "请求过于频繁,可稍后重试",
106
+ }
107
+ ),
108
+ "INTERNAL_ERROR": MappingProxyType(
109
+ {
110
+ "httpStatus": 500,
111
+ "retryable": False,
112
+ "outcome": "unknown",
113
+ "meaning": "服务内部错误,可能已产生副作用",
114
+ }
115
+ ),
116
+ "LIST_LIMIT_EXCEEDED": MappingProxyType(
117
+ {
118
+ "httpStatus": 500,
119
+ "retryable": False,
120
+ "outcome": "unknown",
121
+ "meaning": "一次性列表的结果超出接口声明的上限",
122
+ }
123
+ ),
124
+ "SERVICE_UNAVAILABLE": MappingProxyType(
125
+ {
126
+ "httpStatus": 503,
127
+ "retryable": True,
128
+ "outcome": "unknown",
129
+ "meaning": "服务或其依赖暂不可用",
130
+ }
131
+ ),
132
+ }
133
+ )
134
+ """通用失败码 → HTTP 状态、能否重试、是否已执行(outcome)与含义。"""
135
+
136
+ BOUNDED_LIST_RESPONSE_PATHS: Final = MappingProxyType({"items": "items"})
137
+ """BoundedList 响应里各字段的路径(由定义 bounded-list.schema.json 生成)。"""
138
+
139
+ CURSOR_LIST_REQUEST_PARAMS: Final = MappingProxyType(
140
+ {"after": "cursor.after", "limit": "cursor.limit"}
141
+ )
142
+ """CursorListRequest 的线上参数名(由定义 cursor-list-request.schema.json 生成)。"""
143
+
144
+ CURSOR_LIST_RESPONSE_PATHS: Final = MappingProxyType(
145
+ {"items": "items", "next": "cursor.next", "hasMore": "cursor.hasMore"}
146
+ )
147
+ """CursorList 响应里各字段的路径(由定义 cursor-list.schema.json 生成)。"""
148
+
149
+ LIST_FILTER_PARAMS: Final = MappingProxyType(
150
+ {"prefix": "filter.", "operators": MappingProxyType({"eq": "eq"})}
151
+ )
152
+ """ListFilter 的线上参数名(由定义 list-filter.schema.json 生成)。"""
153
+
154
+ PAGED_LIST_REQUEST_PARAMS: Final = MappingProxyType(
155
+ {
156
+ "page": "page.page",
157
+ "pageSize": "page.pageSize",
158
+ "query": "page.query",
159
+ "orderBy": "page.orderBy",
160
+ }
161
+ )
162
+ """PagedListRequest 的线上参数名(由定义 paged-list-request.schema.json 生成)。"""
163
+
164
+ PAGED_LIST_RESPONSE_PATHS: Final = MappingProxyType(
165
+ {
166
+ "items": "items",
167
+ "totalRecord": "page.totalRecord",
168
+ "pageSize": "page.pageSize",
169
+ "totalPage": "page.totalPage",
170
+ }
171
+ )
172
+ """PagedList 响应里各字段的路径(由定义 paged-list.schema.json 生成)。"""
@@ -0,0 +1,39 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: cursor-list.json
5
+
6
+ from __future__ import annotations
7
+ from pydantic import ConfigDict, Field, StrictBool, StrictStr
8
+ from typing import Annotated, Any
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class CursorListCursor(SchemaModel):
13
+ """
14
+ 接着取的位置。hasMore 为 true 时必须给 next。
15
+ """
16
+
17
+ model_config = ConfigDict(
18
+ extra="forbid",
19
+ )
20
+ next: Annotated[StrictStr | None, Field(max_length=1024, min_length=1)] = None
21
+ """
22
+ 下一批的游标,对调用方不透明,1–1024 个字符;没有更多时可省略。
23
+ """
24
+ hasMore: StrictBool
25
+ """
26
+ 是否还有更多。
27
+ """
28
+
29
+
30
+ class CursorList(SchemaModel):
31
+ """
32
+ 游标式列表,作成功外壳的 data:消息流这类接着往下取的列表,不带总数。取数方向由各接口声明。顶层允许接口自己声明的附带字段,但不得重复表达翻页信息;不带 page。
33
+ """
34
+
35
+ items: list[Any]
36
+ """
37
+ 本批数据。
38
+ """
39
+ cursor: CursorListCursor
@@ -0,0 +1,27 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: cursor-list-request.json
5
+
6
+ from __future__ import annotations
7
+ from pydantic import ConfigDict, Field, StrictInt, StrictStr
8
+ from typing import Annotated
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class CursorListRequest(SchemaModel):
13
+ """
14
+ 游标式列表的请求参数。线上以 cursor. 前缀的查询参数传递(如 cursor.limit=20),本定义约束解码后的对象;前缀下未声明的参数不合法。
15
+ """
16
+
17
+ model_config = ConfigDict(
18
+ extra="forbid",
19
+ )
20
+ after: Annotated[StrictStr | None, Field(max_length=1024, min_length=1)] = None
21
+ """
22
+ 上一批返回的 next,1–1024 个字符;首批不带。
23
+ """
24
+ limit: Annotated[StrictInt | None, Field(ge=1, le=100)] = None
25
+ """
26
+ 本批最多取多少条;缺省值由各接口自定。
27
+ """
@@ -0,0 +1,99 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: error-body.json
5
+
6
+ from __future__ import annotations
7
+ from typing import Annotated, Literal
8
+ from pydantic import ConfigDict, Field, StrictBool, StrictStr
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class ErrorField(SchemaModel):
13
+ """
14
+ 一项出错的输入。in 为 body 时用 pointer 定位、不能有 parameter;其他位置用 parameter 定位、不能有 pointer。
15
+ """
16
+
17
+ model_config = ConfigDict(
18
+ extra="forbid",
19
+ )
20
+ in_: Annotated[
21
+ Literal["body", "query", "path", "header", "cookie"], Field(alias="in")
22
+ ]
23
+ """
24
+ 出错输入所在的位置。
25
+ """
26
+ code: Annotated[StrictStr, Field(pattern="^[A-Za-z][A-Za-z0-9_.\\-]{0,127}$")]
27
+ """
28
+ 字段级错误码:字母开头,只含字母、数字、下划线、点、短横线,1–128 个字符。
29
+ """
30
+ message: Annotated[StrictStr, Field(max_length=1000, pattern="\\S")]
31
+ """
32
+ 说明,不能是纯空白。
33
+ """
34
+ pointer: Annotated[
35
+ StrictStr | None,
36
+ Field(
37
+ pattern="^(?:(?:/(?:[^~/]|~[01])*)*/(?:(?:[^~/]|~[01])*(?:[^~/\\n]|~[01]))?)?$"
38
+ ),
39
+ ] = None
40
+ """
41
+ 请求体内的位置,RFC 6901 JSON Pointer。
42
+ """
43
+ parameter: Annotated[StrictStr | None, Field(max_length=256, min_length=1)] = None
44
+ """
45
+ 参数名,1–256 个字符。
46
+ """
47
+
48
+
49
+ class ErrorDetail(SchemaModel):
50
+ """
51
+ 错误的处置信息。
52
+ """
53
+
54
+ model_config = ConfigDict(
55
+ extra="forbid",
56
+ )
57
+ retryable: StrictBool
58
+ """
59
+ 原样重试是否可能成功。
60
+ """
61
+ outcome: Literal["not_executed", "unknown"]
62
+ """
63
+ not_executed:确定没有执行;unknown:可能已产生副作用。
64
+ """
65
+ fields: list[ErrorField] | None = None
66
+ """
67
+ 逐项指出出错的输入;可以是空数组。
68
+ """
69
+
70
+
71
+ class ErrorBody(SchemaModel):
72
+ """
73
+ 错误体。HTTP 状态表达大类,包体带业务码、说明、能否重试、是否已执行与出错字段定位。code 是通用失败码时,retryable 与 outcome 必须与通用失败码表一致。
74
+ """
75
+
76
+ model_config = ConfigDict(
77
+ extra="forbid",
78
+ )
79
+ code: Annotated[StrictStr, Field(pattern="^[A-Za-z][A-Za-z0-9_]{0,127}$")]
80
+ """
81
+ 业务码,开放字符串:字母开头,只含字母、数字、下划线,1–128 个字符;不能是 OK。使用方遇到不认识的码按 HTTP 状态归类处理。
82
+ """
83
+ message: Annotated[StrictStr, Field(max_length=1000, pattern="\\S")]
84
+ """
85
+ 说明,不能是纯空白。
86
+ """
87
+ data: None
88
+ """
89
+ 错误体恒为 null。
90
+ """
91
+ error: ErrorDetail
92
+ requestId: Annotated[StrictStr, Field(pattern="^\\S{1,128}$")]
93
+ """
94
+ 请求标识,1–128 个字符,不含空白字符。
95
+ """
96
+ detail: StrictStr | None = None
97
+ """
98
+ 补充说明,可选,不限长。
99
+ """
@@ -0,0 +1,55 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: list-filter.json
5
+
6
+ from __future__ import annotations
7
+ from pydantic import (
8
+ ConfigDict,
9
+ Field,
10
+ RootModel,
11
+ StrictBool,
12
+ StrictFloat,
13
+ StrictStr,
14
+ StringConstraints,
15
+ )
16
+ from done_coding_schema_api._base import SchemaModel
17
+ from typing import Annotated
18
+
19
+
20
+ class ListFilterCondition(SchemaModel):
21
+ """
22
+ 一个字段上的筛选条件,至少一个操作。
23
+ """
24
+
25
+ model_config = ConfigDict(
26
+ extra="forbid",
27
+ )
28
+ eq: StrictStr | StrictFloat | StrictBool | None = None
29
+ """
30
+ 等于;值为标量。
31
+ """
32
+
33
+
34
+ class ListFilter(
35
+ RootModel[
36
+ dict[
37
+ Annotated[
38
+ str, StringConstraints(pattern=r"^[a-z][a-zA-Z0-9]*$", strict=True)
39
+ ],
40
+ ListFilterCondition,
41
+ ]
42
+ ]
43
+ ):
44
+ root: Annotated[
45
+ dict[
46
+ Annotated[
47
+ str, StringConstraints(pattern=r"^[a-z][a-zA-Z0-9]*$", strict=True)
48
+ ],
49
+ ListFilterCondition,
50
+ ],
51
+ Field(title="ListFilter"),
52
+ ]
53
+ """
54
+ 列表的筛选参数。线上写作 filter.<字段>.<操作>(如 filter.status.eq=active),本定义约束解码后的对象 {<字段>: {<操作>: 值}};字段为小驼峰,可筛选哪些字段由接口自己声明。首版操作只有 eq。前缀下未声明的参数不合法。
55
+ """
@@ -0,0 +1,43 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: paged-list.json
5
+
6
+ from __future__ import annotations
7
+ from pydantic import ConfigDict, Field, StrictInt
8
+ from typing import Annotated, Any
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class PagedListPage(SchemaModel):
13
+ """
14
+ 翻页信息。不回传当前页码。totalPage 等于 ceil(totalRecord / pageSize),总数为 0 时为 0(x-totalPageEqualsCeil)。
15
+ """
16
+
17
+ model_config = ConfigDict(
18
+ extra="forbid",
19
+ )
20
+ totalRecord: Annotated[StrictInt, Field(ge=0)]
21
+ """
22
+ 总条数。
23
+ """
24
+ pageSize: Annotated[StrictInt, Field(ge=1, le=100)]
25
+ """
26
+ 每页条数,回显请求值。
27
+ """
28
+ totalPage: Annotated[StrictInt, Field(ge=0)]
29
+ """
30
+ 总页数。
31
+ """
32
+
33
+
34
+ class PagedList(SchemaModel):
35
+ """
36
+ 页码式列表,作成功外壳的 data:给人翻页的表格,能跳页、有总数。顶层允许接口自己声明的附带字段,但不得重复表达翻页信息;不带 cursor。
37
+ """
38
+
39
+ items: list[Any]
40
+ """
41
+ 当前页的数据。
42
+ """
43
+ page: PagedListPage
@@ -0,0 +1,41 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: paged-list-request.json
5
+
6
+ from __future__ import annotations
7
+ from pydantic import ConfigDict, Field, StrictInt, StrictStr
8
+ from typing import Annotated
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class PagedListRequest(SchemaModel):
13
+ """
14
+ 页码式列表的请求参数。线上以 page. 前缀的查询参数传递(如 page.pageSize=20),本定义约束解码后的对象;前缀下未声明的参数不合法。
15
+ """
16
+
17
+ model_config = ConfigDict(
18
+ extra="forbid",
19
+ )
20
+ page: Annotated[StrictInt | None, Field(ge=1)] = 1
21
+ """
22
+ 页码,从 1 开始。
23
+ """
24
+ pageSize: Annotated[StrictInt | None, Field(ge=1, le=100)] = 10
25
+ """
26
+ 每页条数。
27
+ """
28
+ query: Annotated[StrictStr | None, Field(max_length=200)] = None
29
+ """
30
+ 模糊搜索词,最多 200 个字符。
31
+ """
32
+ orderBy: Annotated[
33
+ StrictStr | None,
34
+ Field(
35
+ max_length=200,
36
+ pattern="^[a-z][a-zA-Z0-9]*(?: (?:asc|desc))?(?:, ?[a-z][a-zA-Z0-9]*(?: (?:asc|desc))?)*$",
37
+ ),
38
+ ] = None
39
+ """
40
+ 排序:逗号分隔,每段是小驼峰字段名,后面可跟一个空格加 asc 或 desc(缺省 asc);逗号后可有一个空格;最多 200 个字符。
41
+ """
@@ -0,0 +1,77 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: service-error-codes.json
5
+
6
+ from __future__ import annotations
7
+ from pydantic import ConfigDict, Field, RootModel, StrictBool, StrictInt, StrictStr
8
+ from typing import Annotated, Literal
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class AdditionalHttpStatus(RootModel[StrictInt]):
13
+ root: Annotated[StrictInt, Field(ge=400, le=599)]
14
+
15
+
16
+ class ServiceErrorCode(SchemaModel):
17
+ """
18
+ 一个专有码。stage 为 execute 时不得有 httpStatus 与 additionalHttpStatuses;为 accept 或 both 时必须有 httpStatus。additionalHttpStatuses 不含主状态(x-arrayExcludesProperty)。
19
+ """
20
+
21
+ model_config = ConfigDict(
22
+ extra="forbid",
23
+ )
24
+ code: Annotated[
25
+ StrictStr,
26
+ Field(
27
+ max_length=128,
28
+ pattern="^(?:[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*|[a-z][a-z0-9]*(?:_[a-z0-9]+)*)$",
29
+ ),
30
+ ]
31
+ """
32
+ 码:整体大写下划线或整体小写下划线写法,字母开头,不以下划线结尾,不含连续下划线,最长 128 个字符。
33
+ """
34
+ stage: Literal["accept", "execute", "both"]
35
+ """
36
+ accept:受理时同步返回;execute:异步执行阶段产生;both:两者都有。
37
+ """
38
+ httpStatus: Annotated[StrictInt | None, Field(ge=400, le=599)] = None
39
+ """
40
+ 主 HTTP 状态,4xx 或 5xx。
41
+ """
42
+ additionalHttpStatuses: Annotated[
43
+ list[AdditionalHttpStatus] | None, Field(min_length=1)
44
+ ] = None
45
+ """
46
+ 同一个码在不同情形下的其他 HTTP 状态:至少 1 项、不重复、不含主状态。
47
+ """
48
+ retryable: StrictBool
49
+ """
50
+ 原样重试是否可能成功。
51
+ """
52
+ outcome: Literal["not_executed", "unknown"]
53
+ """
54
+ not_executed:确定没有执行;unknown:可能已产生副作用。
55
+ """
56
+ meaning: Annotated[StrictStr, Field(max_length=1000, min_length=1)]
57
+ """
58
+ 一句话含义,1–1000 个字符。
59
+ """
60
+
61
+
62
+ class ServiceErrorCodes(SchemaModel):
63
+ """
64
+ 一个服务的专有业务码清单。不得重新定义通用码;OK 与 HTTP_<数字> 形式的码保留,不得使用;比较按字节精确进行,不做大小写归一。
65
+ """
66
+
67
+ model_config = ConfigDict(
68
+ extra="forbid",
69
+ )
70
+ service: Annotated[StrictStr, Field(pattern="^[a-z][a-z0-9\\-]{0,63}$")]
71
+ """
72
+ 服务标识:小写字母开头,只含小写字母、数字、短横线,最长 64 个字符。
73
+ """
74
+ codes: Annotated[list[ServiceErrorCode], Field(min_length=1)]
75
+ """
76
+ 专有码,至少 1 项;code 在清单内不重复(x-uniqueItemsBy)。
77
+ """
@@ -0,0 +1,31 @@
1
+ # 本文件由 scripts/generate.mjs 依据 schemas/ 的定义生成,勿手改。
2
+ # 改了定义后在仓根运行 pnpm gen;pnpm check:generated 会核对本文件与定义一致。
3
+ # generated by datamodel-codegen:
4
+ # filename: success-envelope.json
5
+
6
+ from __future__ import annotations
7
+ from typing import Annotated, Any, Literal
8
+ from pydantic import ConfigDict, Field, StrictStr
9
+ from done_coding_schema_api._base import SchemaModel
10
+
11
+
12
+ class SuccessEnvelope(SchemaModel):
13
+ """
14
+ 成功外壳。成功与否、新建还是已受理以 HTTP 状态码为准,code 不随 200 / 201 / 202 变化。
15
+ """
16
+
17
+ model_config = ConfigDict(
18
+ extra="forbid",
19
+ )
20
+ code: Literal["OK"]
21
+ """
22
+ 成功码,恒为 OK。
23
+ """
24
+ message: Annotated[StrictStr, Field(max_length=1000)]
25
+ """
26
+ 说明,可以为空串。
27
+ """
28
+ data: dict[str, Any] | None
29
+ """
30
+ 结果对象或 null;标量结果也包成对象(如 {"count": 3})。
31
+ """
@@ -0,0 +1,179 @@
1
+ """生成模型之上的薄包装(手写)。
2
+
3
+ 只做两件事,不新增、不改名、不放宽任何字段:
4
+
5
+ 1. 成功外壳与三种列表做成泛型:只把 ``data``、``items`` 的类型换成类型参数,
6
+ 便于写 ``SuccessEnvelope[PagedList[User]]``;
7
+ 2. 补上生成工具表达不了的约束:定义里的 if / then / else、not,以及标准 JSON Schema
8
+ 写不出、用 x- 关键字声明的跨字段约束(语义见仓根 scripts/lib/validator.mjs)。
9
+
10
+ 嵌套结构的约束在顶层模型上检查(如页码式的 totalPage 在 ``PagedList`` 上检查),
11
+ 单独使用生成的嵌套模型时不含这些检查。同一组样例同时跑生成模型与本层,
12
+ 差异逐条登记在 tests/test_examples.py 的 GENERATED_GAPS 里。
13
+ """
14
+
15
+ import re
16
+ from typing import Any, Generic
17
+
18
+ from pydantic import BaseModel, model_validator
19
+ from typing_extensions import TypeVar
20
+
21
+ from ._generated import bounded_list as _bounded
22
+ from ._generated import cursor_list as _cursor
23
+ from ._generated import error_body as _error
24
+ from ._generated import list_filter as _filter
25
+ from ._generated import paged_list as _paged
26
+ from ._generated import service_error_codes as _service
27
+ from ._generated import success_envelope as _success
28
+ from ._generated.constants import COMMON_ERROR_CODE_TABLE, COMMON_ERROR_CODES
29
+
30
+ DataT = TypeVar(
31
+ "DataT",
32
+ bound=BaseModel | dict[str, Any] | None,
33
+ default=dict[str, Any] | None,
34
+ )
35
+ ItemT = TypeVar("ItemT", default=Any)
36
+
37
+ _RESERVED_HTTP_CODE = re.compile(r"^HTTP_[0-9]+$")
38
+
39
+
40
+ def _forbid_keys(data: Any, keys: tuple[str, ...], what: str) -> Any:
41
+ """「不得出现」的字段(定义里写作 false)。"""
42
+ if isinstance(data, dict):
43
+ present = [key for key in keys if key in data]
44
+ if present:
45
+ raise ValueError(f"{what}不得带 {'、'.join(present)}")
46
+ return data
47
+
48
+
49
+ class SuccessEnvelope(_success.SuccessEnvelope, Generic[DataT]):
50
+ """成功外壳。``DataT`` 是结果对象的类型(或 None)。"""
51
+
52
+ data: DataT
53
+
54
+
55
+ class BoundedList(_bounded.BoundedList, Generic[ItemT]):
56
+ """一次性列表。``ItemT`` 是元素类型。"""
57
+
58
+ items: list[ItemT]
59
+
60
+ @model_validator(mode="before")
61
+ @classmethod
62
+ def _no_paging(cls, data: Any) -> Any:
63
+ return _forbid_keys(data, ("page", "cursor"), "一次性列表")
64
+
65
+
66
+ class PagedList(_paged.PagedList, Generic[ItemT]):
67
+ """页码式列表。``ItemT`` 是元素类型。"""
68
+
69
+ items: list[ItemT]
70
+
71
+ @model_validator(mode="before")
72
+ @classmethod
73
+ def _no_cursor(cls, data: Any) -> Any:
74
+ return _forbid_keys(data, ("cursor",), "页码式列表")
75
+
76
+ @model_validator(mode="after")
77
+ def _total_page(self) -> "PagedList[ItemT]":
78
+ # x-totalPageEqualsCeil;总数为 0 时 totalPage 为 0 也由此保证。
79
+ page = self.page
80
+ expected = -(-page.totalRecord // page.pageSize)
81
+ if page.totalPage != expected:
82
+ raise ValueError(
83
+ f"totalPage 应为 ceil(totalRecord / pageSize) = {expected}"
84
+ )
85
+ return self
86
+
87
+
88
+ class CursorList(_cursor.CursorList, Generic[ItemT]):
89
+ """游标式列表。``ItemT`` 是元素类型。"""
90
+
91
+ items: list[ItemT]
92
+
93
+ @model_validator(mode="before")
94
+ @classmethod
95
+ def _no_page(cls, data: Any) -> Any:
96
+ return _forbid_keys(data, ("page",), "游标式列表")
97
+
98
+ @model_validator(mode="after")
99
+ def _next_when_more(self) -> "CursorList[ItemT]":
100
+ if self.cursor.hasMore and self.cursor.next is None:
101
+ raise ValueError("hasMore 为 true 时必须给 next")
102
+ return self
103
+
104
+
105
+ class ErrorBody(_error.ErrorBody):
106
+ """错误体。"""
107
+
108
+ @model_validator(mode="after")
109
+ def _semantics(self) -> "ErrorBody":
110
+ if self.code == "OK":
111
+ raise ValueError("错误体的 code 不能是 OK")
112
+ row = COMMON_ERROR_CODE_TABLE.get(self.code)
113
+ if row is not None and (
114
+ self.error.retryable != row["retryable"]
115
+ or self.error.outcome != row["outcome"]
116
+ ):
117
+ raise ValueError(
118
+ f"{self.code} 的 retryable / outcome 须为 "
119
+ f"{row['retryable']} / {row['outcome']}"
120
+ )
121
+ for index, field in enumerate(self.error.fields or []):
122
+ if field.in_ == "body":
123
+ if field.pointer is None or field.parameter is not None:
124
+ raise ValueError(
125
+ f"error.fields[{index}]:in 为 body 时须有 pointer、"
126
+ "不能有 parameter"
127
+ )
128
+ elif field.parameter is None or field.pointer is not None:
129
+ raise ValueError(
130
+ f"error.fields[{index}]:in 不为 body 时须有 parameter、"
131
+ "不能有 pointer"
132
+ )
133
+ return self
134
+
135
+
136
+ class ListFilter(_filter.ListFilter):
137
+ """筛选参数。"""
138
+
139
+ @model_validator(mode="after")
140
+ def _conditions(self) -> "ListFilter":
141
+ for name, condition in self.root.items():
142
+ if not condition.model_fields_set:
143
+ raise ValueError(f"{name}:筛选条件至少要有一个操作")
144
+ return self
145
+
146
+
147
+ class ServiceErrorCodes(_service.ServiceErrorCodes):
148
+ """一个服务的专有业务码清单。"""
149
+
150
+ @model_validator(mode="after")
151
+ def _codes(self) -> "ServiceErrorCodes":
152
+ seen: dict[str, int] = {}
153
+ for index, item in enumerate(self.codes):
154
+ where = f"codes[{index}]"
155
+ # 与 OK、HTTP_<数字>、通用码按字节比较,不做大小写归一。
156
+ if (
157
+ item.code == "OK"
158
+ or _RESERVED_HTTP_CODE.match(item.code)
159
+ or item.code in COMMON_ERROR_CODES
160
+ ):
161
+ raise ValueError(f"{where}:{item.code} 是保留码或通用码")
162
+ if item.stage == "execute":
163
+ if item.httpStatus is not None or item.additionalHttpStatuses:
164
+ raise ValueError(
165
+ f"{where}:execute 不得有 httpStatus 与 additionalHttpStatuses"
166
+ )
167
+ elif item.httpStatus is None:
168
+ raise ValueError(f"{where}:{item.stage} 必须有 httpStatus")
169
+ extra = [status.root for status in item.additionalHttpStatuses or []]
170
+ if len(set(extra)) != len(extra):
171
+ raise ValueError(f"{where}:additionalHttpStatuses 有重复")
172
+ if item.httpStatus in extra:
173
+ # x-arrayExcludesProperty
174
+ raise ValueError(f"{where}:additionalHttpStatuses 不能含主状态")
175
+ if item.code in seen:
176
+ # x-uniqueItemsBy
177
+ raise ValueError(f"{where}:code 与第 {seen[item.code]} 项重复")
178
+ seen[item.code] = index
179
+ return self
File without changes
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: done-coding-schema-api
3
+ Version: 0.0.1a0
4
+ Summary: 跨前后端通用接口结构的 Pydantic 模型与常量
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: pydantic>=2.11,<3
8
+ Requires-Dist: typing-extensions>=4.12
9
+ Requires-Python: >=3.10
10
+ Project-URL: Repository, https://github.com/done-coding/done-coding-schema
11
+ Description-Content-Type: text/markdown
12
+
13
+ # done-coding-schema-api
14
+
15
+ 跨前后端通用接口结构的 Pydantic 模型与常量:成功外壳、错误体、三种列表(一次性 / 页码式 / 游标式)、列表请求参数与业务码,由与 npm 包 `@done-coding/schema-api` 同一份 JSON Schema 定义生成,两包同版本。
16
+
17
+ ## 使用
18
+
19
+ ```bash
20
+ pip install done-coding-schema-api
21
+ ```
22
+
23
+ 需要 Python 3.10 及以上、Pydantic v2(2.11 及以上)。
24
+
25
+ ```python
26
+ from pydantic import BaseModel
27
+
28
+ from done_coding_schema_api import PagedList, SuccessEnvelope
29
+
30
+
31
+ class User(BaseModel):
32
+ id: str
33
+ name: str
34
+
35
+
36
+ UserPage = SuccessEnvelope[PagedList[User]] # 可直接用作接口的返回类型
37
+ ```
38
+
39
+ 模型是严格类型的,结构里的跨字段约束(如 `totalPage` 等于 `ceil(totalRecord / pageSize)`)也已包含在内。
40
+
41
+ 各结构的说明、怎么选列表、业务码与版本规则见仓库 README:<https://github.com/done-coding/done-coding-schema#readme>
@@ -0,0 +1,19 @@
1
+ done_coding_schema_api/__init__.py,sha256=k_V-Hu8cq2TLZ5R31uIPTn3To_YwccJ-9AGS0d6UqKg,1834
2
+ done_coding_schema_api/_base.py,sha256=ZH08Ye1t1J31dMiCBxU42ymebimxNlMrIvjXwhFsixQ,1615
3
+ done_coding_schema_api/_generated/__init__.py,sha256=a2_8_6lt-XhUgTx8Uf8_uOcUVk6OitDfxyAc9OY98OI,237
4
+ done_coding_schema_api/_generated/bounded_list.py,sha256=94NvKUVnc9RBdlnp68mRPXiiRDdHDjn1SPOschHHygw,802
5
+ done_coding_schema_api/_generated/constants.py,sha256=YO_52Ohimxa_oTozHk68h1Y33I30tQ5-V-PnDxKB70g,5844
6
+ done_coding_schema_api/_generated/cursor_list.py,sha256=BcFlnTTjkhuSqaX3g02nhBQBeYThrAHlfpgnPiGY8s4,1252
7
+ done_coding_schema_api/_generated/cursor_list_request.py,sha256=NewJqRhT4VjHRmycGR_kJrlXQtqi2ipxPLcjzHF0DoM,1054
8
+ done_coding_schema_api/_generated/error_body.py,sha256=g-fUVfTiwTCyWEMYAFy-h5N9COngQyZYe0fvG6N8suU,3098
9
+ done_coding_schema_api/_generated/list_filter.py,sha256=JOWJFtpPq1yDMqnxmw5D5ad_7zi_GvhWVw5BLGkoq0k,1566
10
+ done_coding_schema_api/_generated/paged_list.py,sha256=L9cqfsgXBQhnAJ0f7SF19OvcaaIRnieg_fgnrA3NLDs,1288
11
+ done_coding_schema_api/_generated/paged_list_request.py,sha256=jgvfOj4-aSjqjXIuFce41rKY8LTn8LBh7E3xCszt3e4,1482
12
+ done_coding_schema_api/_generated/service_error_codes.py,sha256=JpVMudcXH-Y1bIHnv_GZCTumaMCn9luPTRpn7TRmtnU,2801
13
+ done_coding_schema_api/_generated/success_envelope.py,sha256=EACfdHkyEJyWuZLV9-h0qo4JOE1XbCDH4EvUGm5WlKU,977
14
+ done_coding_schema_api/models.py,sha256=2XNMy8oRhfxizucaGOdsBwtBDEbDakV5qyzQ2sE3SR0,6815
15
+ done_coding_schema_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ done_coding_schema_api-0.0.1a0.dist-info/licenses/LICENSE,sha256=H5_Pfw2VGi1DBGCH3es4dlv0Y3voprYBCe4rU0vL3-I,1068
17
+ done_coding_schema_api-0.0.1a0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
18
+ done_coding_schema_api-0.0.1a0.dist-info/METADATA,sha256=2KFwCScMDAcWntrlGUD3J7CQEp5ExrRq9p3vhfrjdeM,1342
19
+ done_coding_schema_api-0.0.1a0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 done-coding
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.