Skip to content

Instantly share code, notes, and snippets.

@dittos dittos/app.py
Created Sep 2, 2014

Embed
What would you like to do?
class Handler(BaseHandler):
@property
def db(self):
if not hasattr(self, '_db'):
self._db = Session(bind=self.app.engine)
return self._db
def teardown_request(self):
db = getattr(self, '_db', None)
if db:
db.close()
def serialize_posts(posts):
return dict(data=map(PostSerializer, posts))
class PostSerializer(Serializer):
id = Integer()
title = String()
body = String()
class PostsHandler(Handler):
@argument('limit', type=int)
@responder(serialize_posts)
def get(self, limit):
if limit is None:
limit = self.app.config['DEFAULT_LIMIT']
return self.db.query(Post).limit(limit).order_by(Post.id.desc())
class PostHandler(Handler):
responder = PostSerializer
@argument('id', type=int)
def before_request(self, id):
super(PostHandler, self).before_request(self)
self._post = self.db.query(Post).get(id)
if not self._post:
raise NotFound()
def get(self):
return self._post
@argument('title')
@argument('body')
def put(self, title, body):
if title is not None:
self._post.title = title
if body is not None:
self._post.body = body
self.db.commit()
return self._post
app = App(handlers=(
('/posts', PostsHandler),
('/posts/<id>', PostHandler),
))
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.