Last active
May 13, 2021 17:16
-
-
Save w0rm/3907294 to your computer and use it in GitHub Desktop.
RESTful controller with web.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To create new resource
To update resource by id
To delete resource by id