forked from iti-framework/iTi-Flask
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any, Optional
|
|
|
|
|
|
def summarize_response_json(obj: dict, items_sample_size: int) -> dict:
|
|
"""
|
|
将 {data:{items,page}} 结构中的 items 做摘要:保留数量与前 N 条示例。
|
|
其他结构原样返回。
|
|
"""
|
|
try:
|
|
if isinstance(obj, dict) and isinstance(obj.get("data"), dict):
|
|
data = obj["data"]
|
|
if isinstance(data.get("items"), list):
|
|
items = data["items"]
|
|
return {
|
|
**obj,
|
|
"data": {
|
|
**data,
|
|
"items": {
|
|
"count": len(items),
|
|
"sample": items[:items_sample_size],
|
|
},
|
|
},
|
|
}
|
|
return obj
|
|
except Exception:
|
|
return obj
|
|
|
|
|
|
def safe_json_dumps(value: Any, ensure_ascii: bool = False, max_chars: Optional[int] = None) -> str:
|
|
"""
|
|
安全转字符串:优先 JSON 编码,不可编码时退回 str();可选截断。
|
|
"""
|
|
try:
|
|
text = json.dumps(value, ensure_ascii=ensure_ascii)
|
|
except Exception:
|
|
text = str(value)
|
|
if max_chars is not None and max_chars > 0:
|
|
return text[:max_chars]
|
|
return text
|
|
|
|
|
|
def truncate_text(text: Optional[str], max_chars: int) -> str:
|
|
if not text:
|
|
return ""
|
|
return text[:max_chars]
|
|
|
|
|