Skip to content

Commit f3e5f26

Browse files
committed
refactor: enhance JSON serialization with custom serializer for datetime and Decimal types
1 parent 0ef5ccc commit f3e5f26

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

apps/tools/migrations/internal_tool.sql

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,15 @@ def query_mysql(host,port, user, password, database, sql):
6666
import pymysql
6767
import json
6868
from pymysql.cursors import DictCursor
69+
from datetime import datetime, date
70+
71+
def default_serializer(obj):
72+
from decimal import Decimal
73+
if isinstance(obj, (datetime, date)):
74+
return obj.isoformat() # 将 datetime/date 转换为 ISO 格式字符串
75+
elif isinstance(obj, Decimal):
76+
return float(obj) # 将 Decimal 转换为 float
77+
raise TypeError(f"Type {type(obj)} not serializable")
6978

7079
try:
7180
# 创建连接
@@ -94,7 +103,7 @@ def query_mysql(host,port, user, password, database, sql):
94103
row[key] = value.decode("utf-8") # 转换为字符串
95104

96105
# 将数据序列化为 JSON
97-
json_data = json.dumps(data, ensure_ascii=False)
106+
json_data = json.dumps(data, default=default_serializer, ensure_ascii=False)
98107
return json_data
99108

100109
# 关闭数据库连接
@@ -111,8 +120,11 @@ def queryPgSQL(database, user, password, host, port, query):
111120
112121
# 自定义 JSON 序列化函数
113122
def default_serializer(obj):
123+
from decimal import Decimal
114124
if isinstance(obj, datetime):
115125
return obj.isoformat() # 将 datetime 转换为 ISO 格式字符串
126+
elif isinstance(obj, Decimal):
127+
return float(obj) # 将 Decimal 转换为 float
116128
raise TypeError(f"Type {type(obj)} not serializable")
117129
118130
# 数据库连接信息

0 commit comments

Comments
 (0)