Table of Contents
Create, read, update and delete, the four basic functions of persistent storage, is easily modelled using WebCore.
First, create a class that represents a resource:
class Resource(web.core.Controller):
def __init__(self, id):
"Load up the database record for this instance."
self.record = model.Resource.get(id)
super(Resource, self).__init__()
def index(self):
pass # ... read
def delete(self):
pass # ...
def update(self):
pass # ...
Now to list records, create new ones, and access specific records, you create a top-level controller:
class Resources(web.core.Controller):
def index(self):
pass # ... list
def create(self):
pass # ...
def __lookup__(self, id, *args, **kw):
"Load up the appropriate Resource controller and keep going from there."
web.core.request.path_info_pop() # we consume one path element
return Resource(id), args
Now requests like the following will work (if you map Resources to ‘resource’ in your root controller):
REST stands for “Representational State Transfer”, a way of applying a distinct set of methods to “resources”. In HTTP these methods are: GET, PUT, POST, and DELETE. Each has a distinct meaning in one of two contexts: (from Wikipedia)
You may notice the similarity to the previous section’s CRUD layout, and is, in fact, a more specific example of it. WebDAV is an example of a complete system written with this structure. To implement RESTful services in WebCore you use a combination of the techniques described by CRUD and a helper class.
The HTTPMethod helper class understands all HTTP verbs: get, put, post, delete, head, trace, and options, with head and options written for you.
At its most light-weight, the HTTPMethod helper class allows you to create a separation between the presentation of a form and the processing of the data returned by the form. Take the following example controller:
class SignInMethod(web.core.HTTPMethod):
def get(self):
return "myapp.templates.signin", dict()
def post(self, username, password):
# handle form input
class RootController(web.core.Controller):
login = SignInMethod()