SQLAlchemy REST Serialization

2024-09-25 08:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

在阅读sqlalchemy的文档时,我看到了序列化部分。
我想知道是否有可能使用xml序列化器将sa模型与像Jax-RS这样的Rest web服务相匹配
有一个django扩展处理这个问题:django_roa
你知道这种东西是不是已经为sqlalchemy开发出来了,或者是否有可能做到这一点??
谢谢


Tags: django文档模型restweb序列化sqlalchemysa
2条回答

sqlalchemy.ext.serializer的存在是为了支持查询、表达式和其他内部SQLAlchemy对象的pickling(使用pickle模块),它不处理模型对象。它决不会帮助您将模型对象序列化为XML。可能像pyxser这样的东西对你有用。在

距离完全符合RFC2616还有很长的路要走,但是对于一个原型,我做了如下操作:

from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, backref, sessionmaker
from sqlalchemy.sql.expression import desc
import web
import json

DB_PATH = 'sqlite:////tmp/test.db'

Base = declarative_base()

class LocalClient(Base):
    __tablename__ = 'local_clients'
    __jsonexport__ = ['id', 'name', 'password']

    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True, nullable=False) 
    password = Column(String)

    def __init__(self, name, password):
        self.name = name
        self.password = password

    def __repr__(self):
        return "<LocalClient('%s', '%s')>" % (self.name, self.password)

urls = (
    '/a/LocalClient', 'LocalClientsController'
)

class Encoder(json.JSONEncoder):
    '''This class contains the JSON serializer function for user defined types'''
    def default(self, obj):
        '''This function uses the __jsonexport__ list of relevant attributes to serialize the objects that inherits Base'''
        if isinstance(obj, Base):
            return dict(zip(obj.__jsonexport__, [getattr(obj, v) for v in obj.__jsonexport__]))
        return json.JSONEncoder.default(self, obj)

class LocalClientsController:
    '''The generic RESTful Local Clients Controller'''
    def GET(self):
        '''Returns a JSON list of LocalClients'''
        engine = create_engine(DB_PATH, echo=False)
        Session = sessionmaker(bind=engine)
        session = Session()
        clis = session.query(LocalClient)
        return json.dumps([c for c in clis], cls=Encoder)

相关问题 更多 >