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)
sqlalchemy.ext.serializer
的存在是为了支持查询、表达式和其他内部SQLAlchemy对象的pickling(使用pickle
模块),它不处理模型对象。它决不会帮助您将模型对象序列化为XML。可能像pyxser这样的东西对你有用。在距离完全符合RFC2616还有很长的路要走,但是对于一个原型,我做了如下操作:
相关问题 更多 >
编程相关推荐