如何用Peewee冻结含UUID字段的Postgres表并解决UUID序列化报错
Peewee DataSet UUID字段JSON序列化失败解决方案
你遇到的是Peewee的DataSet组件默认JSON序列化不支持UUID类型的问题,可通过以下两种方案解决:
方案1:传入自定义JSON编码器(推荐)
freeze()方法支持传入自定义的JSON编码器参数,你只需要提前定义可处理UUID类型的编码器即可,无需修改表结构或定义Model:
import json from uuid import UUID from peewee import DataSet class UUIDSupportEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, UUID): # 所有UUID类型直接转为字符串输出 return str(obj) return super().default(obj) data_set = DataSet(conn) data_set["map_sources"].freeze( filename="frozen_gis.json", format="json", encoder=UUIDSupportEncoder )
方案2:预处理行数据后再冻结
如果需要同时处理其他特殊类型数据,可先遍历所有行做数据转换,再把处理后的数据传入freeze():
from uuid import UUID from peewee import DataSet data_set = DataSet(conn) source_table = data_set["map_sources"] processed_data = [] for row in source_table: new_row = {} for key, value in row.items(): if isinstance(value, UUID): new_row[key] = str(value) continue new_row[key] = value processed_data.append(new_row) data_set.freeze( data=processed_data, filename="frozen_gis.json", format="json" )
内容的提问来源于stack exchange,提问作者Oren_C
相关产品推荐
相关产品推荐

