Skip to content
eponvert edited this page Apr 2, 2012 · 4 revisions

Controllers

Controllers glue a Resource to the backend behind it by implementing methods for each declared request. A Controller is implemented against a specific version of a resource, and further declares a sub-version within that version, to track semantic changes.

Like Resources, Controllers can inherit from the Controller implemented for a previous version to enable easy evolution. Various mix-in controllers will be available to interface with common backend frameworks (such as HasDbMeta).

Example

from mesh.standard import *
from yourorganzation.persistence import storage

class ExampleController(Controller):
    resource = Example
    version = (1, 0)

    @classmethod
    def acquire(cls, subject):
        if subject is None:
            return None
        else:
            return storage.get_by_id('example', subject)

    def get(self, context, response, subject, data):
        return response(subject)

    def query(self, context, response, subject, data):
        all_examples = storage.get_all('example')
        response({'resources': all_examples, 'total': len(all_examples)})

    def delete(self, context, response, subject, data):
        storage.delete_by_id(subject['id'])

    ...

Acquire

The methods implementing endpoints take as parameters a context, a subject and data -- a dictionary of request data. For methods particular to a particular resource, the subject parameter should refer to this resource. This is brokered by the acquire class method, whose roll is to look-up a resource by the subject ID provided, and convert it into a resource object.

For instance in a request of /example/2/delete, the acquire method is called on parameter 2, looks up the corresponding resource and returns it; this passes the resource object downstream, so that the subject parameter in the delete method (which is invoked by the request URL) now points to the resource object with ID = 2.

Clone this wiki locally