[Python]Transform the entity result to JSON

本文介绍了如何使用SQLAlchemy的引擎、会话和查询API,并展示了如何将查询结果转换为JSON格式。通过示例代码,详细说明了创建引擎、会话以及操作数据库的基本步骤,最后将查询结果以JSON形式呈现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 :-)'


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值