在编程中,常常需要把一个对象转换成一个json或是一个字典类型。在使用sqlalchemy时,定义的表对象需要把他们转换成字典类型,字典到json的格式转换就很方便了
def to_dict(dumyself):
result = {}
for a in dir(dumyself):
# filter inner field by fieldname
if a.startswith('_') or a == 'metadata':
continue
v = getattr(dumyself, a)
# filter inner field by value type
if callable(v):
continue
if type(v) not in (types.NoneType, types.IntType, types.LongType, types.StringType, types.UnicodeType):
continue
result[a] = getattr(dumyself, a)
return result
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。过滤掉_(下划线)开头的属性、方法,过滤掉metadata,过滤掉函数方法。使用getattr()获取对应的属性值,并写入到字典中,最终返回
Base = declarative_base()
Base.to_dict = to_dict
class Miner(Base):
__tablename__ = 'miners_t'
id = Column(Integer, primary_key=True)
name = Column(String(48), nullable=False, index=True)
ip = Column(String(20), nullable=False) # ip
port = Column(Integer, nullable=False) # port
domain_id = Column(Integer) # domain
location_id = Column(Integer, index=True)
deleted = Column(Integer, nullable=False, server_default="0")
created_at = Column(Integer, nullable=False)
_i = Index("ip_port_idx", poolx_ip, poolx_port)
对象转字典小结:
1.过滤属性名和属性类型,得到符合要求的字段
2.获取字段对应的值
3.按照格式填充值