До полного соответствия 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)