Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Owner

To create new resource

curl -X POST  -H "Content-Type: application/json" -d '{"title":"a title","description":"a description","type":"a type","author":"an author"}' -i http://localhost:8080/resources/

To update resource by id

curl -X PUT  -H "Content-Type: application/json" -d '{"id":"23", "title":"a title","description":"a description","type":"a type","author":"an author"}' -i http://localhost:8080/resources/23

To delete resource by id

curl -X DELETE http://localhost:8080/resources/23
@w0rm
Owner

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
Something went wrong with that request. Please try again.