clare 0.2.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.
- clare/__init__.py +24 -0
- clare/core/__init__.py +24 -0
- clare/core/_optional.py +26 -0
- clare/core/exceptions/__init__.py +7 -0
- clare/core/exceptions/api_exception.py +11 -0
- clare/core/models/__init__.py +7 -0
- clare/core/models/api_response.py +29 -0
- clare/core/utils/__init__.py +88 -0
- clare/core/utils/checks.py +91 -0
- clare/core/utils/containers.py +117 -0
- clare/core/utils/dates.py +92 -0
- clare/core/utils/decorators.py +108 -0
- clare/core/utils/http_client.py +83 -0
- clare/core/utils/ids.py +48 -0
- clare/core/utils/strings.py +56 -0
- clare/py.typed +0 -0
- clare/web/__init__.py +15 -0
- clare/web/handlers.py +24 -0
- clare-0.2.0.dist-info/METADATA +135 -0
- clare-0.2.0.dist-info/RECORD +22 -0
- clare-0.2.0.dist-info/WHEEL +4 -0
- clare-0.2.0.dist-info/licenses/LICENSE +21 -0
clare/__init__.py
ADDED
|
@@ -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
|
+
]
|
clare/core/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""clare 的通用部分 —— 不依赖任何 Web 框架。
|
|
2
|
+
|
|
3
|
+
这里只放框架无关的能力:`utils`(工具函数)、`models`(数据模型)、
|
|
4
|
+
`exceptions`(业务异常)。FastAPI 的集成在 `clare.web`,
|
|
5
|
+
它只单向依赖本包,core 不反向依赖它。
|
|
6
|
+
|
|
7
|
+
对外仍由顶层 `clare` 重导出全部符号;`clare.core` 自身也是自洽的入口,
|
|
8
|
+
`from clare.core import snake_case` 与 `from clare.core.utils.dates import date_range`
|
|
9
|
+
都能直接用。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from . import exceptions, models, utils
|
|
13
|
+
from .exceptions.api_exception import APIException
|
|
14
|
+
from .models.api_response import APIResponse
|
|
15
|
+
from .utils import * # noqa: F403
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
*utils.__all__,
|
|
19
|
+
"APIException",
|
|
20
|
+
"APIResponse",
|
|
21
|
+
"exceptions",
|
|
22
|
+
"models",
|
|
23
|
+
"utils",
|
|
24
|
+
]
|
clare/core/_optional.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""可选依赖的延迟加载,统一给出可执行的安装提示。"""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
__all__ = ["require"]
|
|
7
|
+
|
|
8
|
+
_EXTRA_OF: dict[str, str] = {
|
|
9
|
+
"fastapi": "web",
|
|
10
|
+
"httpx": "http",
|
|
11
|
+
"starlette": "web",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def require(module: str) -> Any:
|
|
16
|
+
"""按需导入可选依赖,缺失时抛出带安装命令的 ImportError。"""
|
|
17
|
+
try:
|
|
18
|
+
return import_module(module)
|
|
19
|
+
except ImportError as exc:
|
|
20
|
+
hint = _install_hint(module)
|
|
21
|
+
raise ImportError(f"clare 的该功能需要 {module},请先安装:{hint}") from exc
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _install_hint(module: str) -> str:
|
|
25
|
+
extra = _EXTRA_OF.get(module)
|
|
26
|
+
return f'pip install "clare[{extra}]"' if extra else f"pip install {module}"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from pydantic import BaseModel, ConfigDict
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class APIResponse[T](BaseModel):
|
|
5
|
+
code: int
|
|
6
|
+
message: str
|
|
7
|
+
data: T | None = None
|
|
8
|
+
|
|
9
|
+
model_config = ConfigDict(extra="ignore")
|
|
10
|
+
|
|
11
|
+
@classmethod
|
|
12
|
+
def success(
|
|
13
|
+
cls,
|
|
14
|
+
*,
|
|
15
|
+
code: int = 0,
|
|
16
|
+
message: str = "success",
|
|
17
|
+
data: T | None = None,
|
|
18
|
+
) -> APIResponse[T]:
|
|
19
|
+
return cls(code=code, message=message, data=data)
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def fail(
|
|
23
|
+
cls,
|
|
24
|
+
*,
|
|
25
|
+
code: int = 1,
|
|
26
|
+
message: str = "fail",
|
|
27
|
+
data: T | None = None,
|
|
28
|
+
) -> APIResponse[T]:
|
|
29
|
+
return cls(code=code, message=message, data=data)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""clare.utils —— 通用工具函数(字符串 / 容器 / 校验 / ID / 时间 / 装饰器 / HTTP)。"""
|
|
2
|
+
|
|
3
|
+
from . import checks, containers, dates, decorators, http_client, ids, strings
|
|
4
|
+
from .checks import (
|
|
5
|
+
ensure_list,
|
|
6
|
+
is_blank,
|
|
7
|
+
is_empty,
|
|
8
|
+
is_iterable,
|
|
9
|
+
safe_cast,
|
|
10
|
+
to_bool,
|
|
11
|
+
to_float,
|
|
12
|
+
to_int,
|
|
13
|
+
)
|
|
14
|
+
from .containers import (
|
|
15
|
+
chunk,
|
|
16
|
+
deep_get,
|
|
17
|
+
deep_merge,
|
|
18
|
+
deep_set,
|
|
19
|
+
group_by,
|
|
20
|
+
unique,
|
|
21
|
+
unique_by,
|
|
22
|
+
)
|
|
23
|
+
from .dates import (
|
|
24
|
+
format_datetime,
|
|
25
|
+
from_timestamp,
|
|
26
|
+
now,
|
|
27
|
+
parse_datetime,
|
|
28
|
+
start_of_day,
|
|
29
|
+
to_timestamp,
|
|
30
|
+
)
|
|
31
|
+
from .decorators import memoize, retry, singleton, timer
|
|
32
|
+
from .http_client import HttpClient, get_json, post_json
|
|
33
|
+
from .ids import is_valid_uuid, short_id, token_hex, token_urlsafe, uuid_str
|
|
34
|
+
from .strings import (
|
|
35
|
+
mask,
|
|
36
|
+
normalize_space,
|
|
37
|
+
random_string,
|
|
38
|
+
slugify,
|
|
39
|
+
truncate,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"HttpClient",
|
|
44
|
+
"checks",
|
|
45
|
+
"chunk",
|
|
46
|
+
"containers",
|
|
47
|
+
"dates",
|
|
48
|
+
"decorators",
|
|
49
|
+
"deep_get",
|
|
50
|
+
"deep_merge",
|
|
51
|
+
"deep_set",
|
|
52
|
+
"ensure_list",
|
|
53
|
+
"format_datetime",
|
|
54
|
+
"from_timestamp",
|
|
55
|
+
"get_json",
|
|
56
|
+
"group_by",
|
|
57
|
+
"http_client",
|
|
58
|
+
"ids",
|
|
59
|
+
"is_blank",
|
|
60
|
+
"is_empty",
|
|
61
|
+
"is_iterable",
|
|
62
|
+
"is_valid_uuid",
|
|
63
|
+
"mask",
|
|
64
|
+
"memoize",
|
|
65
|
+
"normalize_space",
|
|
66
|
+
"now",
|
|
67
|
+
"parse_datetime",
|
|
68
|
+
"post_json",
|
|
69
|
+
"random_string",
|
|
70
|
+
"retry",
|
|
71
|
+
"safe_cast",
|
|
72
|
+
"short_id",
|
|
73
|
+
"singleton",
|
|
74
|
+
"slugify",
|
|
75
|
+
"start_of_day",
|
|
76
|
+
"strings",
|
|
77
|
+
"timer",
|
|
78
|
+
"to_bool",
|
|
79
|
+
"to_float",
|
|
80
|
+
"to_int",
|
|
81
|
+
"to_timestamp",
|
|
82
|
+
"token_hex",
|
|
83
|
+
"token_urlsafe",
|
|
84
|
+
"truncate",
|
|
85
|
+
"unique",
|
|
86
|
+
"unique_by",
|
|
87
|
+
"uuid_str",
|
|
88
|
+
]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""类型判断与安全转换。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable, Sized
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ensure_list",
|
|
8
|
+
"is_blank",
|
|
9
|
+
"is_empty",
|
|
10
|
+
"is_iterable",
|
|
11
|
+
"safe_cast",
|
|
12
|
+
"to_bool",
|
|
13
|
+
"to_float",
|
|
14
|
+
"to_int",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
_TRUE_VALUES = frozenset({"1", "true", "t", "yes", "y", "on"})
|
|
18
|
+
_FALSE_VALUES = frozenset({"0", "false", "f", "no", "n", "off", "none", "null", ""})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def to_bool(value: Any) -> bool:
|
|
22
|
+
"""把常见真值表示转为 bool,无法识别的字符串按非空即真处理。"""
|
|
23
|
+
if isinstance(value, bool):
|
|
24
|
+
return value
|
|
25
|
+
if isinstance(value, (int, float)):
|
|
26
|
+
return value != 0
|
|
27
|
+
if isinstance(value, str):
|
|
28
|
+
normalized = value.strip().lower()
|
|
29
|
+
if normalized in _TRUE_VALUES:
|
|
30
|
+
return True
|
|
31
|
+
if normalized in _FALSE_VALUES:
|
|
32
|
+
return False
|
|
33
|
+
return bool(value)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def to_int(value: Any, default: int = 0) -> int:
|
|
37
|
+
"""转为 int,失败返回 default;小数部分直接截断,整数型字符串含 "1e2" 也可解析。"""
|
|
38
|
+
try:
|
|
39
|
+
return int(float(value))
|
|
40
|
+
except TypeError, ValueError:
|
|
41
|
+
return default
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def to_float(value: Any, default: float = 0.0) -> float:
|
|
45
|
+
"""转为 float,失败返回 default。"""
|
|
46
|
+
try:
|
|
47
|
+
return float(value)
|
|
48
|
+
except TypeError, ValueError:
|
|
49
|
+
return default
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def safe_cast[T](
|
|
53
|
+
value: Any, target: Callable[[Any], T], default: T | None = None
|
|
54
|
+
) -> T | None:
|
|
55
|
+
"""调用 target(value) 做转换,抛类型或取值异常时返回 default。"""
|
|
56
|
+
try:
|
|
57
|
+
return target(value)
|
|
58
|
+
except TypeError, ValueError:
|
|
59
|
+
return default
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def is_empty(value: Any) -> bool:
|
|
63
|
+
"""None、空字符串、空序列/字典/集合视为空;0、False 不算空。"""
|
|
64
|
+
if value is None:
|
|
65
|
+
return True
|
|
66
|
+
if isinstance(value, Sized):
|
|
67
|
+
return len(value) == 0
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def is_blank(value: Any) -> bool:
|
|
72
|
+
"""None 或纯空白字符串视为空白。"""
|
|
73
|
+
return value is None or not str(value).strip()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_iterable(value: Any) -> bool:
|
|
77
|
+
"""判断是否可迭代,字符串与字节按标量处理返回 False,避免逐字符遍历。"""
|
|
78
|
+
if isinstance(value, (str, bytes)):
|
|
79
|
+
return False
|
|
80
|
+
return isinstance(value, Iterable)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def ensure_list(value: Any) -> list:
|
|
84
|
+
"""None 返回空列表,列表原样返回,字符串按单元素处理,其余可迭代对象转为列表。"""
|
|
85
|
+
if value is None:
|
|
86
|
+
return []
|
|
87
|
+
if isinstance(value, list):
|
|
88
|
+
return value
|
|
89
|
+
if isinstance(value, (str, bytes)) or not isinstance(value, Iterable):
|
|
90
|
+
return [value]
|
|
91
|
+
return list(value)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""容器与迭代工具。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import (
|
|
4
|
+
Callable,
|
|
5
|
+
Hashable,
|
|
6
|
+
Iterable,
|
|
7
|
+
Iterator,
|
|
8
|
+
Mapping,
|
|
9
|
+
MutableMapping,
|
|
10
|
+
Sequence,
|
|
11
|
+
)
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"chunk",
|
|
16
|
+
"deep_get",
|
|
17
|
+
"deep_merge",
|
|
18
|
+
"deep_set",
|
|
19
|
+
"group_by",
|
|
20
|
+
"unique",
|
|
21
|
+
"unique_by",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def deep_merge(base: Mapping, override: Mapping) -> dict:
|
|
26
|
+
"""递归合并两个字典,override 优先,返回新字典且不修改入参。"""
|
|
27
|
+
result = dict(base)
|
|
28
|
+
for key, value in override.items():
|
|
29
|
+
current = result.get(key)
|
|
30
|
+
if isinstance(current, Mapping) and isinstance(value, Mapping):
|
|
31
|
+
result[key] = deep_merge(current, value)
|
|
32
|
+
else:
|
|
33
|
+
result[key] = value
|
|
34
|
+
return result
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def deep_get(data: Any, path: str, default: Any = None, sep: str = ".") -> Any:
|
|
38
|
+
"""按 "a.b.0" 这样的路径取值,任一层缺失即返回 default。
|
|
39
|
+
|
|
40
|
+
路径以 sep 分隔,键中若含 sep 字符则无法正确取值。
|
|
41
|
+
"""
|
|
42
|
+
if not path:
|
|
43
|
+
return default
|
|
44
|
+
current = data
|
|
45
|
+
for key in str(path).split(sep):
|
|
46
|
+
if isinstance(current, Mapping):
|
|
47
|
+
if key not in current:
|
|
48
|
+
return default
|
|
49
|
+
current = current[key]
|
|
50
|
+
elif isinstance(current, Sequence) and not isinstance(current, (str, bytes)):
|
|
51
|
+
try:
|
|
52
|
+
current = current[int(key)]
|
|
53
|
+
except ValueError, IndexError:
|
|
54
|
+
return default
|
|
55
|
+
else:
|
|
56
|
+
return default
|
|
57
|
+
return current
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def deep_set(
|
|
61
|
+
data: MutableMapping, path: str, value: Any, sep: str = "."
|
|
62
|
+
) -> MutableMapping:
|
|
63
|
+
"""按路径写入,中间层缺失或类型不符时自动创建为字典。
|
|
64
|
+
|
|
65
|
+
路径以 sep 分隔,键中若含 sep 字符则无法正确写入。空路径抛 ValueError。
|
|
66
|
+
"""
|
|
67
|
+
if not path:
|
|
68
|
+
raise ValueError("path 不能为空")
|
|
69
|
+
keys = str(path).split(sep)
|
|
70
|
+
current = data
|
|
71
|
+
for key in keys[:-1]:
|
|
72
|
+
child = current.get(key)
|
|
73
|
+
if not isinstance(child, MutableMapping):
|
|
74
|
+
child = {}
|
|
75
|
+
current[key] = child
|
|
76
|
+
current = child
|
|
77
|
+
current[keys[-1]] = value
|
|
78
|
+
return data
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def chunk[T](items: Iterable[T], size: int) -> Iterator[list[T]]:
|
|
82
|
+
"""按固定长度切分序列,最后一块可能不足。"""
|
|
83
|
+
if size <= 0:
|
|
84
|
+
raise ValueError("size 必须大于 0")
|
|
85
|
+
batch: list[T] = []
|
|
86
|
+
for item in items:
|
|
87
|
+
batch.append(item)
|
|
88
|
+
if len(batch) == size:
|
|
89
|
+
yield batch
|
|
90
|
+
batch = []
|
|
91
|
+
if batch:
|
|
92
|
+
yield batch
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def group_by[T, K](items: Iterable[T], key: Callable[[T], K]) -> dict[K, list[T]]:
|
|
96
|
+
"""按 key 函数分组,组内保持原顺序。"""
|
|
97
|
+
groups: dict[K, list[T]] = {}
|
|
98
|
+
for item in items:
|
|
99
|
+
groups.setdefault(key(item), []).append(item)
|
|
100
|
+
return groups
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def unique[T](items: Iterable[T]) -> list[T]:
|
|
104
|
+
"""去重并保持首次出现的顺序,要求元素可哈希。"""
|
|
105
|
+
return list(dict.fromkeys(items))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def unique_by[T](items: Iterable[T], key: Callable[[T], Hashable]) -> list[T]:
|
|
109
|
+
"""按 key 去重并保持首次出现的顺序。"""
|
|
110
|
+
seen: set[Hashable] = set()
|
|
111
|
+
result: list[T] = []
|
|
112
|
+
for item in items:
|
|
113
|
+
marker = key(item)
|
|
114
|
+
if marker not in seen:
|
|
115
|
+
seen.add(marker)
|
|
116
|
+
result.append(item)
|
|
117
|
+
return result
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""日期时间工具,默认以带时区的 UTC 为基准。"""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, date, datetime, timezone
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"format_datetime",
|
|
8
|
+
"from_timestamp",
|
|
9
|
+
"now",
|
|
10
|
+
"parse_datetime",
|
|
11
|
+
"start_of_day",
|
|
12
|
+
"to_timestamp",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
_FALLBACK_FORMATS = (
|
|
16
|
+
"%Y-%m-%d %H:%M:%S",
|
|
17
|
+
"%Y-%m-%dT%H:%M:%S",
|
|
18
|
+
"%Y-%m-%d %H:%M",
|
|
19
|
+
"%Y/%m/%d %H:%M:%S",
|
|
20
|
+
"%Y/%m/%d",
|
|
21
|
+
"%Y-%m-%d",
|
|
22
|
+
"%Y%m%d",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def now(tz: timezone | None = None) -> datetime:
|
|
27
|
+
"""当前时间,默认返回带时区的 UTC 时间。"""
|
|
28
|
+
return datetime.now(tz or UTC)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _ensure_utc(dt: datetime) -> datetime:
|
|
32
|
+
if dt.tzinfo is None:
|
|
33
|
+
return dt.replace(tzinfo=UTC)
|
|
34
|
+
return dt
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_datetime(value: Any, default: datetime | None = None) -> datetime | None:
|
|
38
|
+
"""解析日期时间,支持 datetime/date 对象与常见字符串格式,失败返回 default。"""
|
|
39
|
+
if isinstance(value, datetime):
|
|
40
|
+
return value
|
|
41
|
+
if isinstance(value, date):
|
|
42
|
+
return datetime(value.year, value.month, value.day, tzinfo=UTC)
|
|
43
|
+
if not isinstance(value, str):
|
|
44
|
+
return default
|
|
45
|
+
text = value.strip()
|
|
46
|
+
if not text:
|
|
47
|
+
return default
|
|
48
|
+
try:
|
|
49
|
+
return _ensure_utc(datetime.fromisoformat(text))
|
|
50
|
+
except ValueError:
|
|
51
|
+
pass
|
|
52
|
+
for fmt in _FALLBACK_FORMATS:
|
|
53
|
+
try:
|
|
54
|
+
return _ensure_utc(datetime.strptime(text, fmt))
|
|
55
|
+
except ValueError:
|
|
56
|
+
continue
|
|
57
|
+
return default
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def format_datetime(
|
|
61
|
+
value: Any, fmt: str = "%Y-%m-%d %H:%M:%S", default: str = ""
|
|
62
|
+
) -> str:
|
|
63
|
+
"""按 fmt 格式化日期时间,无法解析时返回 default。"""
|
|
64
|
+
parsed = parse_datetime(value)
|
|
65
|
+
return default if parsed is None else parsed.strftime(fmt)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def to_timestamp(value: Any, default: float = 0.0) -> float:
|
|
69
|
+
"""转为 Unix 时间戳(秒),无时区的输入按 UTC 解释。"""
|
|
70
|
+
parsed = parse_datetime(value)
|
|
71
|
+
if parsed is None:
|
|
72
|
+
return default
|
|
73
|
+
if parsed.tzinfo is None:
|
|
74
|
+
parsed = parsed.replace(tzinfo=UTC)
|
|
75
|
+
return parsed.timestamp()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def from_timestamp(timestamp: float, tz: timezone | None = None) -> datetime:
|
|
79
|
+
"""从 Unix 时间戳(秒)还原为 datetime。"""
|
|
80
|
+
return datetime.fromtimestamp(timestamp, tz or UTC)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def start_of_day(value: Any = None) -> datetime:
|
|
84
|
+
"""取当天 00:00:00,保留原时区信息。"""
|
|
85
|
+
return _require(value).replace(hour=0, minute=0, second=0, microsecond=0)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _require(value: Any) -> datetime:
|
|
89
|
+
moment = now() if value is None else parse_datetime(value)
|
|
90
|
+
if moment is None:
|
|
91
|
+
raise ValueError(f"无法解析日期:{value!r}")
|
|
92
|
+
return moment
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""常用函数装饰器。"""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import logging
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
_logger = logging.getLogger("clare")
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"memoize",
|
|
13
|
+
"retry",
|
|
14
|
+
"singleton",
|
|
15
|
+
"timer",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def timer(func: Callable | None = None, *, log: bool = True) -> Callable:
|
|
20
|
+
"""统计函数耗时,可用 @timer 或 @timer(log=False) 两种写法,耗时记录在 last_elapsed 上。"""
|
|
21
|
+
|
|
22
|
+
def decorate(target: Callable) -> Callable:
|
|
23
|
+
@functools.wraps(target)
|
|
24
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
25
|
+
started = time.perf_counter()
|
|
26
|
+
try:
|
|
27
|
+
return target(*args, **kwargs)
|
|
28
|
+
finally:
|
|
29
|
+
elapsed = time.perf_counter() - started
|
|
30
|
+
wrapper.last_elapsed = elapsed # type: ignore[attr-defined]
|
|
31
|
+
if log:
|
|
32
|
+
_logger.info("%s 耗时 %.4fs", target.__qualname__, elapsed)
|
|
33
|
+
|
|
34
|
+
wrapper.last_elapsed = 0.0 # type: ignore[attr-defined]
|
|
35
|
+
return wrapper
|
|
36
|
+
|
|
37
|
+
return decorate(func) if func is not None else decorate
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def retry(
|
|
41
|
+
times: int = 3,
|
|
42
|
+
delay: float = 0.0,
|
|
43
|
+
backoff: float = 2.0,
|
|
44
|
+
exceptions: tuple[type[BaseException], ...] = (Exception,),
|
|
45
|
+
logger: logging.Logger | None = None,
|
|
46
|
+
) -> Callable:
|
|
47
|
+
"""失败后重试,times 为总尝试次数,delay 按 backoff 逐次放大。"""
|
|
48
|
+
if times < 1:
|
|
49
|
+
raise ValueError("times 必须大于等于 1")
|
|
50
|
+
|
|
51
|
+
def decorate(target: Callable) -> Callable:
|
|
52
|
+
@functools.wraps(target)
|
|
53
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
54
|
+
wait = delay
|
|
55
|
+
for attempt in range(1, times + 1):
|
|
56
|
+
try:
|
|
57
|
+
return target(*args, **kwargs)
|
|
58
|
+
except exceptions as exc:
|
|
59
|
+
if attempt >= times:
|
|
60
|
+
raise
|
|
61
|
+
if logger is not None:
|
|
62
|
+
logger.warning(
|
|
63
|
+
"%s 第 %d 次失败:%s", target.__qualname__, attempt, exc
|
|
64
|
+
)
|
|
65
|
+
if wait > 0:
|
|
66
|
+
time.sleep(wait)
|
|
67
|
+
wait *= backoff
|
|
68
|
+
raise RuntimeError(f"{target.__qualname__} 重试逻辑异常")
|
|
69
|
+
|
|
70
|
+
return wrapper
|
|
71
|
+
|
|
72
|
+
return decorate
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def memoize(func: Callable) -> Callable:
|
|
76
|
+
"""按调用参数缓存返回值,参数需可哈希;不可哈希时退化为直接调用。"""
|
|
77
|
+
|
|
78
|
+
def decorate(target: Callable) -> Callable:
|
|
79
|
+
cache: dict[Any, Any] = {}
|
|
80
|
+
|
|
81
|
+
@functools.wraps(target)
|
|
82
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
83
|
+
try:
|
|
84
|
+
key = (args, tuple(sorted(kwargs.items())))
|
|
85
|
+
if key not in cache:
|
|
86
|
+
cache[key] = target(*args, **kwargs)
|
|
87
|
+
except TypeError:
|
|
88
|
+
return target(*args, **kwargs)
|
|
89
|
+
return cache[key]
|
|
90
|
+
|
|
91
|
+
wrapper.cache_clear = cache.clear # type: ignore[attr-defined]
|
|
92
|
+
return wrapper
|
|
93
|
+
|
|
94
|
+
return decorate(func)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def singleton[T](cls: type[T]) -> type[T]:
|
|
98
|
+
"""让类只保留一个实例,重复实例化返回同一对象;__init__ 仍会重复执行。"""
|
|
99
|
+
instances: dict[type, Any] = {}
|
|
100
|
+
original_new = cls.__new__
|
|
101
|
+
|
|
102
|
+
def new(sub_cls: type, *args: Any, **kwargs: Any) -> Any:
|
|
103
|
+
if sub_cls not in instances:
|
|
104
|
+
instances[sub_cls] = original_new(sub_cls)
|
|
105
|
+
return instances[sub_cls]
|
|
106
|
+
|
|
107
|
+
cls.__new__ = staticmethod(new) # type: ignore[assignment]
|
|
108
|
+
return cls
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""基于 httpx 的轻量 HTTP 客户端。
|
|
2
|
+
|
|
3
|
+
httpx 属于可选依赖:未安装时不影响 `import clare`,只在真正发起请求时抛出带安装提示的 ImportError。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .._optional import require
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"HttpClient",
|
|
12
|
+
"get_json",
|
|
13
|
+
"post_json",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
_RETRYABLE_STATUS = 500
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class HttpClient:
|
|
20
|
+
"""带默认超时、统一请求头与失败重试的 HTTP 客户端。"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
base_url: str = "",
|
|
25
|
+
timeout: float = 10.0,
|
|
26
|
+
headers: dict[str, str] | None = None,
|
|
27
|
+
retries: int = 2,
|
|
28
|
+
) -> None:
|
|
29
|
+
self.base_url = base_url.rstrip("/")
|
|
30
|
+
self.timeout = timeout
|
|
31
|
+
self.headers = {"User-Agent": "clare/0.1", **(headers or {})}
|
|
32
|
+
self.retries = max(retries, 0)
|
|
33
|
+
|
|
34
|
+
def request(self, method: str, url: str, **kwargs: Any) -> Any:
|
|
35
|
+
"""发起请求,网络错误与 5xx 响应自动重试,其余状态码由 raise_for_status 抛出。"""
|
|
36
|
+
httpx = require("httpx")
|
|
37
|
+
target = f"{self.base_url}{url}" if self.base_url else url
|
|
38
|
+
options: dict[str, Any] = {
|
|
39
|
+
"timeout": self.timeout,
|
|
40
|
+
"headers": self.headers,
|
|
41
|
+
**kwargs,
|
|
42
|
+
}
|
|
43
|
+
attempts = self.retries + 1
|
|
44
|
+
for attempt in range(1, attempts + 1):
|
|
45
|
+
try:
|
|
46
|
+
response = httpx.request(method, target, **options)
|
|
47
|
+
except httpx.TransportError:
|
|
48
|
+
if attempt >= attempts:
|
|
49
|
+
raise
|
|
50
|
+
continue
|
|
51
|
+
if response.status_code >= _RETRYABLE_STATUS and attempt < attempts:
|
|
52
|
+
continue
|
|
53
|
+
response.raise_for_status()
|
|
54
|
+
return response
|
|
55
|
+
raise RuntimeError(f"请求失败:{target}")
|
|
56
|
+
|
|
57
|
+
def get(self, url: str, **kwargs: Any) -> Any:
|
|
58
|
+
"""发起 GET 请求。"""
|
|
59
|
+
return self.request("GET", url, **kwargs)
|
|
60
|
+
|
|
61
|
+
def post(self, url: str, **kwargs: Any) -> Any:
|
|
62
|
+
"""发起 POST 请求。"""
|
|
63
|
+
return self.request("POST", url, **kwargs)
|
|
64
|
+
|
|
65
|
+
def get_json(self, url: str, **kwargs: Any) -> Any:
|
|
66
|
+
"""发起 GET 请求并解析响应 JSON。"""
|
|
67
|
+
return self.get(url, **kwargs).json()
|
|
68
|
+
|
|
69
|
+
def post_json(self, url: str, payload: Any = None, **kwargs: Any) -> Any:
|
|
70
|
+
"""以 JSON 体发起 POST 请求并解析响应 JSON。"""
|
|
71
|
+
return self.post(url, json=payload, **kwargs).json()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_json(url: str, timeout: float = 10.0, **kwargs: Any) -> Any:
|
|
75
|
+
"""一次性 GET 请求并解析 JSON。"""
|
|
76
|
+
return HttpClient(timeout=timeout).get_json(url, **kwargs)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def post_json(
|
|
80
|
+
url: str, payload: Any = None, timeout: float = 10.0, **kwargs: Any
|
|
81
|
+
) -> Any:
|
|
82
|
+
"""一次性 POST JSON 请求并解析响应 JSON。"""
|
|
83
|
+
return HttpClient(timeout=timeout).post_json(url, payload, **kwargs)
|
clare/core/utils/ids.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""标识符与令牌生成。"""
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import uuid
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"is_valid_uuid",
|
|
9
|
+
"short_id",
|
|
10
|
+
"token_hex",
|
|
11
|
+
"token_urlsafe",
|
|
12
|
+
"uuid_str",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
# 剔除 0/O/1/l/I 等易混淆字符,便于人工转录
|
|
16
|
+
_SAFE_ALPHABET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def uuid_str() -> str:
|
|
20
|
+
"""生成标准 UUID4 字符串。"""
|
|
21
|
+
return str(uuid.uuid4())
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def short_id(length: int = 10, alphabet: str | None = None) -> str:
|
|
25
|
+
"""生成短随机 ID,默认字母表已排除易混淆字符。"""
|
|
26
|
+
if length <= 0:
|
|
27
|
+
raise ValueError("length 必须大于 0")
|
|
28
|
+
chars = alphabet if alphabet else _SAFE_ALPHABET
|
|
29
|
+
return "".join(secrets.choice(chars) for _ in range(length))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def token_hex(nbytes: int = 16) -> str:
|
|
33
|
+
"""生成十六进制随机令牌,长度为 nbytes 的两倍。"""
|
|
34
|
+
return secrets.token_hex(nbytes)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def token_urlsafe(nbytes: int = 16) -> str:
|
|
38
|
+
"""生成 URL 安全的随机令牌。"""
|
|
39
|
+
return secrets.token_urlsafe(nbytes)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_valid_uuid(value: Any, version: int | None = None) -> bool:
|
|
43
|
+
"""校验 UUID 字符串,可指定版本号(如 4)。"""
|
|
44
|
+
try:
|
|
45
|
+
parsed = uuid.UUID(str(value))
|
|
46
|
+
except ValueError, AttributeError, TypeError:
|
|
47
|
+
return False
|
|
48
|
+
return version is None or parsed.version == version
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""字符串处理工具。"""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import secrets
|
|
5
|
+
import string as _string
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"mask",
|
|
9
|
+
"normalize_space",
|
|
10
|
+
"random_string",
|
|
11
|
+
"slugify",
|
|
12
|
+
"truncate",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
_NON_WORD = re.compile(r"[^A-Za-z0-9]+")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def slugify(text: str) -> str:
|
|
19
|
+
"""转换为 URL 友好的 slug,非字母数字字符折叠为单个短横线。"""
|
|
20
|
+
return _NON_WORD.sub("-", text.strip().lower()).strip("-")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def truncate(text: str, length: int = 50, suffix: str = "...") -> str:
|
|
24
|
+
"""截断到指定长度,超长时保留前段并追加 suffix。"""
|
|
25
|
+
if length < 0:
|
|
26
|
+
raise ValueError("length 不能为负数")
|
|
27
|
+
if len(text) <= length:
|
|
28
|
+
return text
|
|
29
|
+
if len(suffix) >= length:
|
|
30
|
+
return suffix[:length]
|
|
31
|
+
return text[: length - len(suffix)] + suffix
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def mask(value: str, keep_start: int = 0, keep_end: int = 0, char: str = "*") -> str:
|
|
35
|
+
"""脱敏保留首尾若干字符,如 mask("13812345678", 3, 4) -> "138****5678"。"""
|
|
36
|
+
if keep_start < 0 or keep_end < 0:
|
|
37
|
+
raise ValueError("keep_start/keep_end 不能为负数")
|
|
38
|
+
if keep_start + keep_end >= len(value):
|
|
39
|
+
return value
|
|
40
|
+
hidden = len(value) - keep_start - keep_end
|
|
41
|
+
return value[:keep_start] + char * hidden + value[len(value) - keep_end :]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def random_string(length: int = 16, alphabet: str | None = None) -> str:
|
|
45
|
+
"""生成随机字符串,默认字母数字组合,使用 secrets 保证密码学安全。"""
|
|
46
|
+
if length <= 0:
|
|
47
|
+
raise ValueError("length 必须大于 0")
|
|
48
|
+
chars = _string.ascii_letters + _string.digits if alphabet is None else alphabet
|
|
49
|
+
if not chars:
|
|
50
|
+
raise ValueError("alphabet 不能为空")
|
|
51
|
+
return "".join(secrets.choice(chars) for _ in range(length))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def normalize_space(text: str) -> str:
|
|
55
|
+
"""把连续空白折叠为单个空格并去除首尾空白。"""
|
|
56
|
+
return re.sub(r"\s+", " ", text).strip()
|
clare/py.typed
ADDED
|
File without changes
|
clare/web/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""FastAPI 集成(需 clare[web])。"""
|
|
2
|
+
|
|
3
|
+
from ..core._optional import require
|
|
4
|
+
|
|
5
|
+
require("fastapi")
|
|
6
|
+
|
|
7
|
+
# 可选依赖必须先校验,故 handlers 的导入不能提到文件顶部
|
|
8
|
+
from . import handlers # noqa: E402
|
|
9
|
+
from .handlers import api_exception_handler, register_exception_handlers # noqa: E402
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"api_exception_handler",
|
|
13
|
+
"handlers",
|
|
14
|
+
"register_exception_handlers",
|
|
15
|
+
]
|
clare/web/handlers.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""把 APIException 转换为统一响应结构的异常处理器。"""
|
|
2
|
+
|
|
3
|
+
from fastapi import FastAPI
|
|
4
|
+
from starlette.requests import Request
|
|
5
|
+
from starlette.responses import JSONResponse
|
|
6
|
+
|
|
7
|
+
from clare.core.exceptions.api_exception import APIException
|
|
8
|
+
from clare.core.models.api_response import APIResponse
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"api_exception_handler",
|
|
12
|
+
"register_exception_handlers",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def api_exception_handler(request: Request, exc: APIException) -> JSONResponse:
|
|
17
|
+
"""把 APIException 转成 {code, message, data} 结构的 JSON 响应。"""
|
|
18
|
+
payload = APIResponse.fail(code=exc.code, message=exc.message)
|
|
19
|
+
return JSONResponse(status_code=exc.status_code, content=payload.model_dump())
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register_exception_handlers(app: FastAPI) -> None:
|
|
23
|
+
"""把 clare 的异常处理器注册到 FastAPI 应用上。"""
|
|
24
|
+
app.add_exception_handler(APIException, api_exception_handler)
|
|
@@ -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
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
clare/__init__.py,sha256=cyOMuRNzIX5Fz-JIWRIpll4jKw3K94yHI4bp5pZhjm8,624
|
|
2
|
+
clare/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
clare/core/__init__.py,sha256=l7o_7aG_Z29jPsi6bo1O5kRmDVHAOqULVyLwZta07IE,778
|
|
4
|
+
clare/core/_optional.py,sha256=Hgnit5rf_XROaQOmG13Ch6eKalKNnOqPn7xPqxmxn5g,747
|
|
5
|
+
clare/core/exceptions/__init__.py,sha256=J13W49SQbcJdcLv_VqQLxJgaQQjFezE0g2lFEHGfVp0,124
|
|
6
|
+
clare/core/exceptions/api_exception.py,sha256=0ereRAcUCjMaBNjOOaxIIeBJthDKaGrqTfOX3b-PTEw,299
|
|
7
|
+
clare/core/models/__init__.py,sha256=S6w9NS7dEuMAtVP44s1LoO2uxXAxtJdq7MMV8EwckSo,119
|
|
8
|
+
clare/core/models/api_response.py,sha256=GcX-ek_9Rk5lyJO1oLVWk13EaLjOHtjPVcOQthjg_vw,636
|
|
9
|
+
clare/core/utils/__init__.py,sha256=oZszR1t6pJ1N48PShn1FpwNVmNiOIEfNUWs3_qqV4jI,1649
|
|
10
|
+
clare/core/utils/checks.py,sha256=VTlX83ozwEc4WtB7qq7xJ0H39b0bhDvsvYT5pi2YxR4,2648
|
|
11
|
+
clare/core/utils/containers.py,sha256=Vr938RTk6sBkToH41DUdy1_c0kdgMOqj9b_uXopRsDE,3337
|
|
12
|
+
clare/core/utils/dates.py,sha256=ayA4dVKL295dQPjKoguGz9PSfYMgIUvJcDyimUdaERk,2654
|
|
13
|
+
clare/core/utils/decorators.py,sha256=SO0bjqC-dJ3z6YLNV-pGKwNLyl6rKqm-q0ewi1xp6DE,3494
|
|
14
|
+
clare/core/utils/http_client.py,sha256=Vd40ZJEd-smLGLoAnicDxa6Zoqw6Yii58d9odA89QNQ,2808
|
|
15
|
+
clare/core/utils/ids.py,sha256=07eVtyUz0v1th1oDiwy3ofswoYtM7LulNRfbW0kfGdY,1351
|
|
16
|
+
clare/core/utils/strings.py,sha256=_DUAS86HmsfY9zEt95mBcCW8jOyQ_nrC25udF6MuBFs,1885
|
|
17
|
+
clare/web/__init__.py,sha256=Mb56-Ai74veFNLHAVdrTZaYN78L6fAcR4qPfHcKwVXM,401
|
|
18
|
+
clare/web/handlers.py,sha256=7s3a-DpGuODGLPlHoZYxj-FXvXN5R9tJ9s0BQ9e3IJQ,893
|
|
19
|
+
clare-0.2.0.dist-info/METADATA,sha256=O9U-sPIqqkz8Zoima6vlLD2CPGdalGLv4HDBDhAlVTI,7287
|
|
20
|
+
clare-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
21
|
+
clare-0.2.0.dist-info/licenses/LICENSE,sha256=QuU8jl2VYxQY8KUwEyx-8iaPxLpaYmULRAlfwQE2_Hw,1069
|
|
22
|
+
clare-0.2.0.dist-info/RECORD,,
|
|
@@ -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.
|