代码迁移

This commit is contained in:
Neo
2025-11-18 02:28:47 +08:00
parent ccf3baca2b
commit 84e80841cd
86 changed files with 185483 additions and 0 deletions

View File

View File

@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""数据类型解析器"""
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP
from dateutil import parser as dtparser
from zoneinfo import ZoneInfo
class TypeParser:
"""类型解析工具"""
@staticmethod
def parse_timestamp(s: str, tz: ZoneInfo) -> datetime | None:
"""解析时间戳"""
if not s:
return None
try:
dt = dtparser.parse(s)
if dt.tzinfo is None:
return dt.replace(tzinfo=tz)
return dt.astimezone(tz)
except Exception:
return None
@staticmethod
def parse_decimal(value, scale: int = 2) -> Decimal | None:
"""解析金额"""
if value is None:
return None
try:
d = Decimal(str(value))
return d.quantize(Decimal(10) ** -scale, rounding=ROUND_HALF_UP)
except Exception:
return None
@staticmethod
def parse_int(value) -> int | None:
"""解析整数"""
if value is None:
return None
try:
return int(value)
except Exception:
return None
@staticmethod
def format_timestamp(dt: datetime | None, tz: ZoneInfo) -> str | None:
"""格式化时间戳"""
if not dt:
return None
return dt.astimezone(tz).strftime("%Y-%m-%d %H:%M:%S")

View File

@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
"""数据验证器"""
from decimal import Decimal
class DataValidator:
"""数据验证工具"""
@staticmethod
def validate_positive_amount(value: Decimal | None, field_name: str = "amount"):
"""验证金额为正数"""
if value is not None and value < 0:
raise ValueError(f"{field_name} 不能为负数: {value}")
@staticmethod
def validate_required(value, field_name: str):
"""验证必填字段"""
if value is None or value == "":
raise ValueError(f"{field_name} 是必填字段")
@staticmethod
def validate_range(value, min_val, max_val, field_name: str):
"""验证值范围"""
if value is not None:
if value < min_val or value > max_val:
raise ValueError(f"{field_name} 必须在 {min_val}{max_val} 之间")