clare 0.2.0__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.
Files changed (38) hide show
  1. clare-0.2.0/.github/workflows/ci.yml +42 -0
  2. clare-0.2.0/.github/workflows/release.yml +24 -0
  3. clare-0.2.0/.gitignore +223 -0
  4. clare-0.2.0/.python-version +1 -0
  5. clare-0.2.0/LICENSE +21 -0
  6. clare-0.2.0/PKG-INFO +135 -0
  7. clare-0.2.0/README.md +115 -0
  8. clare-0.2.0/pyproject.toml +78 -0
  9. clare-0.2.0/src/clare/__init__.py +24 -0
  10. clare-0.2.0/src/clare/core/__init__.py +24 -0
  11. clare-0.2.0/src/clare/core/_optional.py +26 -0
  12. clare-0.2.0/src/clare/core/exceptions/__init__.py +7 -0
  13. clare-0.2.0/src/clare/core/exceptions/api_exception.py +11 -0
  14. clare-0.2.0/src/clare/core/models/__init__.py +7 -0
  15. clare-0.2.0/src/clare/core/models/api_response.py +29 -0
  16. clare-0.2.0/src/clare/core/utils/__init__.py +88 -0
  17. clare-0.2.0/src/clare/core/utils/checks.py +91 -0
  18. clare-0.2.0/src/clare/core/utils/containers.py +117 -0
  19. clare-0.2.0/src/clare/core/utils/dates.py +92 -0
  20. clare-0.2.0/src/clare/core/utils/decorators.py +108 -0
  21. clare-0.2.0/src/clare/core/utils/http_client.py +83 -0
  22. clare-0.2.0/src/clare/core/utils/ids.py +48 -0
  23. clare-0.2.0/src/clare/core/utils/strings.py +56 -0
  24. clare-0.2.0/src/clare/py.typed +0 -0
  25. clare-0.2.0/src/clare/web/__init__.py +15 -0
  26. clare-0.2.0/src/clare/web/handlers.py +24 -0
  27. clare-0.2.0/tests/test_api_response.py +124 -0
  28. clare-0.2.0/tests/test_checks.py +111 -0
  29. clare-0.2.0/tests/test_containers.py +87 -0
  30. clare-0.2.0/tests/test_core_isolation.py +72 -0
  31. clare-0.2.0/tests/test_dates.py +85 -0
  32. clare-0.2.0/tests/test_decorators.py +173 -0
  33. clare-0.2.0/tests/test_http_client.py +151 -0
  34. clare-0.2.0/tests/test_ids.py +67 -0
  35. clare-0.2.0/tests/test_optional.py +36 -0
  36. clare-0.2.0/tests/test_strings.py +78 -0
  37. clare-0.2.0/tests/test_web.py +103 -0
  38. clare-0.2.0/uv.lock +327 -0
@@ -0,0 +1,42 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["**"]
6
+ pull_request:
7
+
8
+ jobs:
9
+ # 裸装:不装任何 extra,除了跑 lint 与 core 用例,还顺带验证
10
+ # 「import clare 不引入任何框架依赖」这条边界(web 用例在此整体跳过)。
11
+ core:
12
+ name: core (无 extra)
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: astral-sh/setup-uv@v3
18
+
19
+ - run: uv python install 3.14
20
+
21
+ - run: uv sync
22
+
23
+ - run: uv run ruff check src tests
24
+
25
+ - run: uv run ruff format --check src tests
26
+
27
+ - run: uv run pytest -v
28
+
29
+ # 全量 extra:真正把 web 的用例跑起来。
30
+ extras:
31
+ name: extras (web)
32
+ runs-on: ubuntu-latest
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+
36
+ - uses: astral-sh/setup-uv@v3
37
+
38
+ - run: uv python install 3.14
39
+
40
+ - run: uv sync --all-extras
41
+
42
+ - run: uv run pytest -v
@@ -0,0 +1,24 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ jobs:
9
+ release:
10
+ runs-on: ubuntu-latest
11
+ permissions:
12
+ id-token: write
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ with:
16
+ fetch-depth: 0
17
+
18
+ - uses: astral-sh/setup-uv@v3
19
+
20
+ - run: uv python install 3.14
21
+
22
+ - run: uv build
23
+
24
+ - uses: pypa/gh-action-pypi-publish@release/v1
clare-0.2.0/.gitignore ADDED
@@ -0,0 +1,223 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
219
+
220
+ .idea
221
+ .workbuddy
222
+ .pytest_tmp
223
+ .pytest_tmp/
@@ -0,0 +1 @@
1
+ 3.14
clare-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 侠客老王
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.
clare-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.5
2
+ Name: clare
3
+ Version: 0.2.0
4
+ Summary: 日常开发工具库
5
+ Author-email: xxwang <78023776@qq.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.14
9
+ Requires-Dist: pydantic>=2.13.5
10
+ Provides-Extra: all
11
+ Requires-Dist: fastapi>=0.115; extra == 'all'
12
+ Requires-Dist: httpx>=0.28.1; extra == 'all'
13
+ Requires-Dist: starlette>=0.40; extra == 'all'
14
+ Provides-Extra: http
15
+ Requires-Dist: httpx>=0.28.1; extra == 'http'
16
+ Provides-Extra: web
17
+ Requires-Dist: fastapi>=0.115; extra == 'web'
18
+ Requires-Dist: starlette>=0.40; extra == 'web'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # clare
22
+
23
+ 日常开发工具库 —— 核心 9 个模块、51 个公开符号,`import clare` 开箱即用。
24
+ FastAPI 集成做成可选 extras,按需安装、互不干扰。
25
+
26
+ ## 安装
27
+
28
+ 需要 Python 3.14 及以上。
29
+
30
+ ```bash
31
+ pip install clare # 核心:仅依赖 pydantic
32
+ pip install "clare[http]" # httpx 请求封装
33
+ pip install "clare[web]" # FastAPI 集成
34
+ pip install "clare[all]" # 以上全部
35
+ ```
36
+
37
+ 可选依赖缺失不影响 `import clare`:只有导入对应子包(或调用 `http_client`)时才失败,
38
+ 错误信息里直接给出该执行的安装命令,例如
39
+ `clare 的该功能需要 httpx,请先安装:pip install "clare[http]"`。
40
+
41
+ ## 快速开始
42
+
43
+ ```python
44
+ import clare
45
+
46
+ clare.mask("13812345678", 3, 4) # '138****5678'
47
+ clare.deep_get({"a": {"b": [1, 2, 3]}}, "a.b.2") # 3
48
+ list(clare.chunk([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
49
+ clare.group_by(["a", "bb", "cc"], len) # {1: ['a'], 2: ['bb', 'cc']}
50
+ clare.dates.now() # 带时区的 UTC 当前时间
51
+ clare.to_timestamp("2026-12-04 18:00:00") # 1796407200.0
52
+ ```
53
+
54
+ 统一响应模型与业务异常:
55
+
56
+ ```python
57
+ from clare import APIException, APIResponse
58
+
59
+ APIResponse.success(
60
+ data={"id": 1}
61
+ ) # APIResponse(code=0, message='success', data={'id': 1})
62
+ APIResponse.fail(
63
+ message="参数错误"
64
+ ) # APIResponse(code=1, message='参数错误', data=None)
65
+
66
+ raise APIException(code=1001, message="余额不足", status_code=400)
67
+ ```
68
+
69
+ ## 模块一览
70
+
71
+ 通用能力全部收在 `clare.core` 下:
72
+
73
+ | 模块 | 用途 | 主要函数 |
74
+ | --- | --- | --- |
75
+ | `core.utils.strings` | 清洗、脱敏、随机串 | `slugify` `truncate` `mask` `normalize_space` `random_string` |
76
+ | `core.utils.containers` | 嵌套结构操作与集合处理 | `deep_merge` `deep_get` `deep_set` `chunk` `group_by` `unique` `unique_by` |
77
+ | `core.utils.checks` | 容错类型转换与判断 | `to_bool` `to_int` `to_float` `safe_cast` `is_empty` `is_blank` `is_iterable` `ensure_list` |
78
+ | `core.utils.ids` | ID 与随机串生成 | `uuid_str` `short_id` `token_hex` `token_urlsafe` `is_valid_uuid` |
79
+ | `core.utils.dates` | 时间解析、格式化与时间戳 | `parse_datetime` `format_datetime` `start_of_day` `now` `to_timestamp` `from_timestamp` |
80
+ | `core.utils.decorators` | 常用函数式装饰器 | `timer` `retry` `memoize` `singleton` |
81
+ | `core.utils.http_client` | 基于 httpx 的请求封装(需 `clare[http]`) | `HttpClient` `get_json` `post_json` |
82
+ | `core.models.api_response` | 统一响应结构 `{code, message, data}` | `APIResponse`(`APIResponse.success` / `APIResponse.fail`) |
83
+ | `core.exceptions.api_exception` | 业务异常,携带响应码与 HTTP 状态码 | `APIException`(`code` `message` `status_code`) |
84
+
85
+ 上表 9 个模块的符号全部在顶层重导出,`import clare` 后直接 `clare.函数名(...)` 调用;
86
+ 也可以按模块导入,如 `from clare import strings`、`from clare import APIResponse`,
87
+ 或直接走通用包的完整路径:`from clare.core.utils.dates import start_of_day`。
88
+
89
+ ### 分层
90
+
91
+ ```
92
+ clare
93
+ ├── core 通用部分 —— 仅依赖 pydantic,零框架依赖
94
+ └── web FastAPI 集成(需 clare[web])
95
+ ```
96
+
97
+ `web` 只**单向**依赖 `core`,core 不反向依赖它 —— 这条边界由 `tests/test_core_isolation.py`
98
+ 用静态扫描守着(core 下出现 `fastapi` / `starlette` 之类的 import,或反向导入 `clare.web`,测试即失败)。
99
+ `clare.core` 自身也是自洽入口,`from clare.core import mask` 可以直接用。
100
+
101
+ 可选子包**不进顶层命名空间**,需要显式导入:
102
+
103
+ | 子包 | 用途 | 主要符号 |
104
+ | --- | --- | --- |
105
+ | `web` | 把 `APIException` 转成统一 JSON 响应(需 `clare[web]`) | `register_exception_handlers` `api_exception_handler` |
106
+
107
+ ## 设计说明
108
+
109
+ - **core 是通用边界**:`clare.core` 只放框架无关的实现,`clare.web` 单向依赖它,顶层 `clare` 只是门面、不含实现。这样「通用部分」是可验证的,不靠约定。
110
+ - **只保留 FastAPI 后台高频能力**:命名风格转换、文件系统工具、`humanize_delta` 这类展示语义函数、吞异常的 `silent` 都已移除 —— 后台服务不生成代码、不直接读本地盘、异常必须显式处理。
111
+ - **仅一个运行时依赖**:`pydantic`(用于 `core.models`)。`http_client` 所需的 httpx 走可选依赖 `clare[http]`,其余全部基于标准库。
112
+ - **延迟导入 httpx**:`http_client` 在函数内部经 `core._optional.require("httpx")` 导入,保证未安装 httpx 时 `import clare` 不失败。
113
+ - **extras 分层不改变 core 契约**:顶层始终 51 个符号,`import clare` 不加载任何可选依赖(实测 `fastapi` / `starlette` / `httpx` 都不进入 `sys.modules`)。`clare.web` 走同一个 `core._optional.require()`,缺依赖时在导入处即刻失败并给出可直接执行的安装命令。
114
+ - **`APIResponse` 只有一对构造入口**:成功 `APIResponse.success(...)`、失败 `APIResponse.fail(...)`,两者均为 keyword-only,`code` / `message` / `data` 都可覆盖。不额外提供模块级 `success` / `fail` 函数,免得把这类通用名注入调用方命名空间。
115
+ - **`code` / `message` 是必填字段**:默认值只由 `success` / `fail` 提供,直接 `APIResponse(...)` 构造时必须显式传入。
116
+ - **默认文案不外泄**:`success` / `fail` 的默认文案写死在签名里,不作模块常量导出 —— 措辞随时可改,导出即成为契约。
117
+ - **`APIResponse.data` 的类型校验需显式参数化**:Python 泛型在运行期拿不到 `T`,`APIResponse.success(data=...)` 不会校验 `data`(JSON schema 里 `data` 为 `Any`);要强校验应写 `APIResponse[Foo](...)` 或 `APIResponse[Foo].success(data=...)`,FastAPI 场景由 `response_model=APIResponse[Foo]` 兜住。
118
+ - **Python 3.14+**:依赖 3.14 的三项语言特性 —— PEP 695(`class APIResponse[T]`、`def chunk[T](...)` 泛型语法)、PEP 649(注解延迟求值)、PEP 758(`except A, B:` 可省略括号)。
119
+ - **模块命名避开标准库**:用 `containers` / `checks` / `dates`,避免与 `collections` / `types` / `datetime` 混淆。
120
+ - `chunk` 返回生成器,按需迭代;需要列表时用 `list(...)` 包裹。
121
+
122
+ ## 开发
123
+
124
+ ```bash
125
+ uv sync # 安装依赖(含 dev 组)
126
+ uv sync --extra web # 需要跑 web 测试时补齐 extras
127
+ uv run pytest # 运行测试
128
+ uv run ruff check src tests # 静态检查
129
+ uv run ruff format --check src tests # 格式检查,只校验不改文件
130
+ uv run ruff format src tests # 自动重排格式
131
+ ```
132
+
133
+ ## License
134
+
135
+ MIT
clare-0.2.0/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # clare
2
+
3
+ 日常开发工具库 —— 核心 9 个模块、51 个公开符号,`import clare` 开箱即用。
4
+ FastAPI 集成做成可选 extras,按需安装、互不干扰。
5
+
6
+ ## 安装
7
+
8
+ 需要 Python 3.14 及以上。
9
+
10
+ ```bash
11
+ pip install clare # 核心:仅依赖 pydantic
12
+ pip install "clare[http]" # httpx 请求封装
13
+ pip install "clare[web]" # FastAPI 集成
14
+ pip install "clare[all]" # 以上全部
15
+ ```
16
+
17
+ 可选依赖缺失不影响 `import clare`:只有导入对应子包(或调用 `http_client`)时才失败,
18
+ 错误信息里直接给出该执行的安装命令,例如
19
+ `clare 的该功能需要 httpx,请先安装:pip install "clare[http]"`。
20
+
21
+ ## 快速开始
22
+
23
+ ```python
24
+ import clare
25
+
26
+ clare.mask("13812345678", 3, 4) # '138****5678'
27
+ clare.deep_get({"a": {"b": [1, 2, 3]}}, "a.b.2") # 3
28
+ list(clare.chunk([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
29
+ clare.group_by(["a", "bb", "cc"], len) # {1: ['a'], 2: ['bb', 'cc']}
30
+ clare.dates.now() # 带时区的 UTC 当前时间
31
+ clare.to_timestamp("2026-12-04 18:00:00") # 1796407200.0
32
+ ```
33
+
34
+ 统一响应模型与业务异常:
35
+
36
+ ```python
37
+ from clare import APIException, APIResponse
38
+
39
+ APIResponse.success(
40
+ data={"id": 1}
41
+ ) # APIResponse(code=0, message='success', data={'id': 1})
42
+ APIResponse.fail(
43
+ message="参数错误"
44
+ ) # APIResponse(code=1, message='参数错误', data=None)
45
+
46
+ raise APIException(code=1001, message="余额不足", status_code=400)
47
+ ```
48
+
49
+ ## 模块一览
50
+
51
+ 通用能力全部收在 `clare.core` 下:
52
+
53
+ | 模块 | 用途 | 主要函数 |
54
+ | --- | --- | --- |
55
+ | `core.utils.strings` | 清洗、脱敏、随机串 | `slugify` `truncate` `mask` `normalize_space` `random_string` |
56
+ | `core.utils.containers` | 嵌套结构操作与集合处理 | `deep_merge` `deep_get` `deep_set` `chunk` `group_by` `unique` `unique_by` |
57
+ | `core.utils.checks` | 容错类型转换与判断 | `to_bool` `to_int` `to_float` `safe_cast` `is_empty` `is_blank` `is_iterable` `ensure_list` |
58
+ | `core.utils.ids` | ID 与随机串生成 | `uuid_str` `short_id` `token_hex` `token_urlsafe` `is_valid_uuid` |
59
+ | `core.utils.dates` | 时间解析、格式化与时间戳 | `parse_datetime` `format_datetime` `start_of_day` `now` `to_timestamp` `from_timestamp` |
60
+ | `core.utils.decorators` | 常用函数式装饰器 | `timer` `retry` `memoize` `singleton` |
61
+ | `core.utils.http_client` | 基于 httpx 的请求封装(需 `clare[http]`) | `HttpClient` `get_json` `post_json` |
62
+ | `core.models.api_response` | 统一响应结构 `{code, message, data}` | `APIResponse`(`APIResponse.success` / `APIResponse.fail`) |
63
+ | `core.exceptions.api_exception` | 业务异常,携带响应码与 HTTP 状态码 | `APIException`(`code` `message` `status_code`) |
64
+
65
+ 上表 9 个模块的符号全部在顶层重导出,`import clare` 后直接 `clare.函数名(...)` 调用;
66
+ 也可以按模块导入,如 `from clare import strings`、`from clare import APIResponse`,
67
+ 或直接走通用包的完整路径:`from clare.core.utils.dates import start_of_day`。
68
+
69
+ ### 分层
70
+
71
+ ```
72
+ clare
73
+ ├── core 通用部分 —— 仅依赖 pydantic,零框架依赖
74
+ └── web FastAPI 集成(需 clare[web])
75
+ ```
76
+
77
+ `web` 只**单向**依赖 `core`,core 不反向依赖它 —— 这条边界由 `tests/test_core_isolation.py`
78
+ 用静态扫描守着(core 下出现 `fastapi` / `starlette` 之类的 import,或反向导入 `clare.web`,测试即失败)。
79
+ `clare.core` 自身也是自洽入口,`from clare.core import mask` 可以直接用。
80
+
81
+ 可选子包**不进顶层命名空间**,需要显式导入:
82
+
83
+ | 子包 | 用途 | 主要符号 |
84
+ | --- | --- | --- |
85
+ | `web` | 把 `APIException` 转成统一 JSON 响应(需 `clare[web]`) | `register_exception_handlers` `api_exception_handler` |
86
+
87
+ ## 设计说明
88
+
89
+ - **core 是通用边界**:`clare.core` 只放框架无关的实现,`clare.web` 单向依赖它,顶层 `clare` 只是门面、不含实现。这样「通用部分」是可验证的,不靠约定。
90
+ - **只保留 FastAPI 后台高频能力**:命名风格转换、文件系统工具、`humanize_delta` 这类展示语义函数、吞异常的 `silent` 都已移除 —— 后台服务不生成代码、不直接读本地盘、异常必须显式处理。
91
+ - **仅一个运行时依赖**:`pydantic`(用于 `core.models`)。`http_client` 所需的 httpx 走可选依赖 `clare[http]`,其余全部基于标准库。
92
+ - **延迟导入 httpx**:`http_client` 在函数内部经 `core._optional.require("httpx")` 导入,保证未安装 httpx 时 `import clare` 不失败。
93
+ - **extras 分层不改变 core 契约**:顶层始终 51 个符号,`import clare` 不加载任何可选依赖(实测 `fastapi` / `starlette` / `httpx` 都不进入 `sys.modules`)。`clare.web` 走同一个 `core._optional.require()`,缺依赖时在导入处即刻失败并给出可直接执行的安装命令。
94
+ - **`APIResponse` 只有一对构造入口**:成功 `APIResponse.success(...)`、失败 `APIResponse.fail(...)`,两者均为 keyword-only,`code` / `message` / `data` 都可覆盖。不额外提供模块级 `success` / `fail` 函数,免得把这类通用名注入调用方命名空间。
95
+ - **`code` / `message` 是必填字段**:默认值只由 `success` / `fail` 提供,直接 `APIResponse(...)` 构造时必须显式传入。
96
+ - **默认文案不外泄**:`success` / `fail` 的默认文案写死在签名里,不作模块常量导出 —— 措辞随时可改,导出即成为契约。
97
+ - **`APIResponse.data` 的类型校验需显式参数化**:Python 泛型在运行期拿不到 `T`,`APIResponse.success(data=...)` 不会校验 `data`(JSON schema 里 `data` 为 `Any`);要强校验应写 `APIResponse[Foo](...)` 或 `APIResponse[Foo].success(data=...)`,FastAPI 场景由 `response_model=APIResponse[Foo]` 兜住。
98
+ - **Python 3.14+**:依赖 3.14 的三项语言特性 —— PEP 695(`class APIResponse[T]`、`def chunk[T](...)` 泛型语法)、PEP 649(注解延迟求值)、PEP 758(`except A, B:` 可省略括号)。
99
+ - **模块命名避开标准库**:用 `containers` / `checks` / `dates`,避免与 `collections` / `types` / `datetime` 混淆。
100
+ - `chunk` 返回生成器,按需迭代;需要列表时用 `list(...)` 包裹。
101
+
102
+ ## 开发
103
+
104
+ ```bash
105
+ uv sync # 安装依赖(含 dev 组)
106
+ uv sync --extra web # 需要跑 web 测试时补齐 extras
107
+ uv run pytest # 运行测试
108
+ uv run ruff check src tests # 静态检查
109
+ uv run ruff format --check src tests # 格式检查,只校验不改文件
110
+ uv run ruff format src tests # 自动重排格式
111
+ ```
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,78 @@
1
+ [project]
2
+ name = "clare"
3
+ description = "日常开发工具库"
4
+ readme = "README.md"
5
+ license = "MIT"
6
+ authors = [
7
+ { name = "xxwang", email = "78023776@qq.com" }
8
+ ]
9
+ requires-python = ">=3.14"
10
+ dynamic = ["version"]
11
+ dependencies = [
12
+ "pydantic>=2.13.5",
13
+ ]
14
+
15
+ [project.optional-dependencies]
16
+ http = [
17
+ "httpx>=0.28.1",
18
+ ]
19
+ web = [
20
+ "fastapi>=0.115",
21
+ "starlette>=0.40",
22
+ ]
23
+ all = [
24
+ "clare[http]",
25
+ "clare[web]",
26
+ ]
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "httpx>=0.28.1",
31
+ "pytest>=8.0",
32
+ "ruff>=0.16.5",
33
+ ]
34
+
35
+ [build-system]
36
+ requires = ["hatchling", "hatch-vcs"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.version]
40
+ source = "vcs"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/clare"]
44
+
45
+ [tool.ruff]
46
+ target-version = "py314"
47
+ line-length = 88
48
+
49
+ [tool.ruff.lint]
50
+ select = [
51
+ "E", # pycodestyle errors
52
+ "W", # pycodestyle warnings
53
+ "F", # pyflakes
54
+ "I", # isort (import 排序)
55
+ "N", # pep8-naming
56
+ "UP", # pyupgrade (语法升级)
57
+ "B", # flake8-bugbear (常见 bug)
58
+ "SIM", # flake8-simplify (代码简化)
59
+ "ASYNC", # flake8-async (异步最佳实践) ← FastAPI 项目必开!
60
+ "RUF", # Ruff 专属规则
61
+ ]
62
+
63
+ ignore = [
64
+ "E501", # 行长度由 formatter 控制
65
+ "RUF001", # 中文日志/文案中的全角标点属正常用法
66
+ "RUF002", # 中文 docstring 中的全角标点属正常用法
67
+ "RUF003", # 中文注释中的全角标点属正常用法
68
+ "B008", # FastAPI 中 Depends(get_session) 的标准写法,非 bug
69
+ "N818", # 异常名有意用 APIException(与 APIResponse 成对),不改名
70
+ "W293"
71
+ ]
72
+
73
+ [tool.ruff.lint.isort]
74
+ known-first-party = ["clare"]
75
+
76
+ [tool.ruff.format]
77
+ quote-style = "double"
78
+ indent-style = "space"
@@ -0,0 +1,24 @@
1
+ """clare —— 日常开发工具库。"""
2
+
3
+ from importlib.metadata import PackageNotFoundError
4
+ from importlib.metadata import version as _package_version
5
+
6
+ from .core import exceptions, models, utils
7
+ from .core.exceptions.api_exception import APIException
8
+ from .core.models.api_response import APIResponse
9
+ from .core.utils import * # noqa: F403
10
+
11
+ try:
12
+ __version__ = _package_version("clare")
13
+ except PackageNotFoundError: # 源码目录未安装时兜底
14
+ __version__ = "0.0.0"
15
+
16
+ __all__ = [
17
+ *utils.__all__,
18
+ "__version__",
19
+ "models",
20
+ "exceptions",
21
+ "utils",
22
+ "APIResponse",
23
+ "APIException",
24
+ ]