[Python]Transform the entity result to JSON
程序员文章站
2022-03-30 21:13:33
this post gives the guide of how to use sqlalchemy's engine, session and query api and cha...
this post gives the guide of how to use sqlalchemy's engine, session and query api and change the results into json format.
from sqlalchemy import create_engine,column,integer,string from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from json import dumps def to_json(model): """ returns a json representation of an sqlalchemy-backed object. """ json = {} json['fields'] = {} json['pk'] = getattr(model, 'id') for col in model._sa_class_manager.mapper.mapped_table.columns: json['fields'][col.name] = getattr(model, col.name) return dumps([json]) engine = create_engine('sqlite:///sqlite.db',echo=true) session = sessionmaker(bind=engine) base = declarative_base() class user(base): __tablename__ = 'user' id = column(integer,primary_key=true) name = column(string) session = session() ''' user = user(id=2,name='developer') session.add(user) session.commit() ''' users = session.query(user).order_by(user.id).all() for user in users: print to_json(user) print '--->done :-)'