chore: 基线提交(重构前代码快照)
- git 初始化 + .gitignore 补全(根 .env / logs / instance / __pycache__ 等) - 修复 utils/.gitignore 误将整个 utils/ 源码层忽略的问题,补入全部工具源码(含 ip2region.xdb) - 含后端全部代码:application / extensions / utils / config / migrations - 含前端 ui/(后续整体迁走) - 不含根 .env(含密钥,本地保留) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
模型工具模块
|
||||
=============================================================
|
||||
|
||||
提供SQLAlchemy模型对象的序列化工具:
|
||||
- model_to_dict: 将单个模型对象转换为字典
|
||||
- models_to_list: 将模型对象列表转换为字典列表
|
||||
- format_datetime: 格式化datetime对象
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from application.constants.common import SERIALIZE_EXCLUDE_FIELDS
|
||||
from utils.case_converter import convert_camel_case
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def format_datetime(dt, format_str='%Y-%m-%d %H:%M:%S'):
|
||||
"""
|
||||
格式化日期时间
|
||||
|
||||
Args:
|
||||
dt: datetime对象
|
||||
format_str: 日期时间格式字符串,默认为 '%Y-%m-%d %H:%M:%S'
|
||||
|
||||
Returns:
|
||||
格式化后的日期字符串,如果输入为None则返回None
|
||||
"""
|
||||
return dt.strftime(format_str) if dt else None
|
||||
|
||||
|
||||
def model_to_dict(model, exclude=None, convert_case=True):
|
||||
"""
|
||||
将SQLAlchemy模型对象转换为字典
|
||||
|
||||
Args:
|
||||
model: SQLAlchemy模型对象
|
||||
exclude: 需要排除的字段列表,如 ['id', 'is_delete'](使用下划线命名)
|
||||
convert_case: 是否将字段名转换为驼峰命名,默认True
|
||||
|
||||
Returns:
|
||||
转换后的字典对象
|
||||
"""
|
||||
if not model:
|
||||
return None
|
||||
|
||||
result = {}
|
||||
for column in model.__table__.columns:
|
||||
field_name = column.name
|
||||
value = getattr(model, field_name)
|
||||
|
||||
if exclude and field_name in exclude:
|
||||
continue
|
||||
|
||||
if field_name in SERIALIZE_EXCLUDE_FIELDS:
|
||||
continue
|
||||
|
||||
# 所有 datetime 类型统一格式化
|
||||
if isinstance(value, datetime):
|
||||
value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None
|
||||
|
||||
if convert_case:
|
||||
field_name = convert_camel_case(field_name)
|
||||
|
||||
result[field_name] = value
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def models_to_list(models, exclude=None, convert_case=True):
|
||||
"""
|
||||
将SQLAlchemy模型对象列表转换为字典列表
|
||||
|
||||
Args:
|
||||
models: SQLAlchemy模型对象列表
|
||||
exclude: 需要排除的字段列表
|
||||
convert_case: 是否将字段名转换为驼峰命名
|
||||
|
||||
Returns:
|
||||
字典列表
|
||||
"""
|
||||
if not models:
|
||||
return []
|
||||
|
||||
return [
|
||||
model_to_dict(model, exclude, convert_case)
|
||||
for model in models
|
||||
]
|
||||
Reference in New Issue
Block a user