Skip to content

Instantly share code, notes, and snippets.

@amcgregor
Created November 24, 2016 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcgregor/d2f68bb2064b0fbdf40b6746f1f4dc45 to your computer and use it in GitHub Desktop.
Save amcgregor/d2f68bb2064b0fbdf40b6746f1f4dc45 to your computer and use it in GitHub Desktop.
"""API sample.
Based on: http://reduxblog.herokuapp.com
See also: https://github.com/marrow/web.dispatch.resource/blob/develop/example/basic.py
Requires: WebCore, web.dispatch.object, web.dispatch.resource
"""
from web.core import Application
from web.ext.serialize import SerializationExtension
from web.dispatch.resource import Collection, Resource
class Post(Resource):
def __init__(self, context, collection, record):
record = {
'id': record, # The ID from the path is passed as "record".
'title': 'Hi!',
'categories': 'Computer, Friends',
'content': 'Blog post content'
}
super(Post).__init__(context, collection, record)
def get(self):
return self._record # This is where it gets saved by Resource.
def post(self, title=None, categories=None, content=None):
"""Update a Post."""
return {'ok': False}
def delete(self):
"""Delete a Post."""
# TODO: Actually delete. ;)
return self._record
class Posts(Collection):
__resource__ = Post # This is the Resource to instantiate for members of this collection.
def get(self):
return [
{ 'id': 1, 'title': 'Hi!', 'categories': 'Computer, Friends' },
{ 'id': 2, 'title': 'New Post', 'categories': 'Candy' }
]
def post(self, id, title, categories, content):
return {'ok': True, 'id': id}
class API:
posts = Posts
class Root:
api = API
app = Application(Root, extensions=[
SerializationExtension()
])
def main():
app.serve('wsgiref')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment