[Python]Transform the entity result to JSON
来源:互联网 发布:淘宝旅行背包 编辑:程序博客网 时间:2024/06/10 01:52
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,Stringfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerfrom 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 :-)'
0 0
- [Python]Transform the entity result to JSON
- An Interactive Guide To The Fourier Transform
- DE19 Introduction to the Laplace Transform
- Entity framework serialize POCO to JSON
- use dynamic sql to output the result
- Caused by: The Result type [json] which is defined in the Result annotation on the class
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "afs" must end with the ';' delimiter.
- The reference to entity "ouml" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter
- The reference to entity "characterEncoding" must end with the ';' delimiter.
- VS2010编译Qt命令
- SQL中遇到多条相同内容只取一条的最简单实现
- 每日一练(四) Billboard (布告牌)
- 基于visual Studio2013解决算法导论之049活动选择问题
- Handler 的执行原理----底层代码
- [Python]Transform the entity result to JSON
- zigbee cc2530功率修改
- 基于visual Studio2013解决算法导论之050强连通分支
- 初学python:《简明python教程》的学习笔记
- NYOJ-85 有趣的数 AC
- 教程3:jsp和servlet配合的简单登录页面login.jsp
- 黑马程序员_Java基础_面向对象(二)_06
- -----周立发----------我曾经用过的源代码-mmap把文件映射到内存
- 黑马程序员-高新技术-注解