赞
踩
# sqlalchemy to json # 只写方法,具体实现流程、数据库连接、数据库表这些内容看前面的文章 # 注:仅供参考,具体情况需具体编写 class AlchemyEncoder(json.JSONEncoder): """ SqlAlchemy对象转换为json格式 """ def default(self, obj): if isinstance(obj.__class__, DeclarativeMeta): fields = {} for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']: data = obj.__getattribute__(field) try: if type(data) is datetime.datetime: data = data.strftime("%Y-%m-%d %H:%M:%S") else: json.dumps(data) fields[field] = data except TypeError: fields[field] = None return fields return json.JSONEncoder.default(self, obj)
- query = server_db.query(from_table).filter(from_table.ID==1).first()
- one_dict = json.loads(json.dumps(query , cls=AlchemyEncoder))
#-----------------------------------------------------------------分一下---------------------------------------------------------------------------#
# json to sqlalchemy
- def set_field(obj_db, data={}):
- for key in obj_db.__class__.__dict__.keys():
- if key.isupper() and key in data:
- setattr(obj_db, key, data[key])
- if hasattr(obj_db, 'INSERTTIME'):
- setattr(obj_db, 'INSERTTIME', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
- osr = arr_table() # arr_table为操作数据库表的orm class对象
- set_field(osr, one_dict) # one_dict为json数据源,前提是json数据和类对象的属性字段相对应,即json的key和数据库表字段相同
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。