Skip to content

Instantly share code, notes, and snippets.

@w0rm
Last active May 13, 2021 17:16
Show Gist options
  • Save w0rm/3907294 to your computer and use it in GitHub Desktop.
Save w0rm/3907294 to your computer and use it in GitHub Desktop.
RESTful controller with web.py
import web
import json
from restful_controller import RESTfulController
urls = (
r'/resources(?:/(?P<resource_id>[0-9]+))?',
'ResourceController',
)
class ResourceController(RESTfulController):
def list(self):
return "list resources", format
def get(self, resource_id):
return "retrieved resource", resource_id
def create(self):
resource = json.loads(web.data())
return "created resource", resource
def update(self, resource_id):
resource = json.loads(web.data())
return "updated resource", resource_id, resource
def delete(self, resource_id):
return "deleted resource", resource_id
app = web.application(urls, globals())
if __name__ == "__main__":
app.run()
import web
class RESTfulController:
methods = ("list", "get", "create", "update", "delete",
"update_collection", "delete_collection")
def __getattr__(self, name):
if name in self.methods and "headers" in web.ctx:
raise web.badrequest()
else:
raise AttributeError
def GET(self, resource_id=None):
if resource_id is None:
return self.list()
else:
return self.get(resource_id)
def POST(self, resource_id=None):
if resource_id is None:
return self.create()
else:
raise web.badrequest()
def PUT(self, resource_id=None):
if resource_id is None:
return self.update_collection()
else:
return self.update(resource_id)
def DELETE(self, resource_id=None):
if resource_id is None:
return self.delete_collection()
else:
return self.delete(resource_id)
@w0rm
Copy link
Author

w0rm commented Apr 8, 2014

A modified version of this code is used in this sample app https://github.com/w0rm/todo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment