Pylons tip #1 – RESTful Web API decorators

I’ve been playing around with implementing REST-ful HTTP APIs under Pylons recently. Something I find myself doing frequently is writing code to restrict the allowed methods for a given URL. For example, a read-only service should generally only allow GET actions while a write service should generally require POST. Its easy to end up with code like this sprinkled in each controller action:

1
2
3
4
5
6
    # writeservice only accepts POST method requests
    def writeservice(self):
        if request.method != 'POST':
            abort(405,  headers=[('Allow', ['POST'])]
        # ...
        pass

One of the handy modules provided by Pylons is REST-ful decorators. This module provides a simple method decorator called pylons.decorators.rest.restrict. This decorator does essentially the same as the above conditional, but normalises it to a shorter block:

1
2
3
4
5
6
7
from pylons.decorators import rest
 
    # writeservice only accepts POST method requests
    @rest.restrict('POST')
    def writeservice(self):
        # ...
        pass

While in the above example, there is not much space savings, when dealing with various API entry points, the @rest.restrict decorator can make things much clearer, less error-prone and even save a modest amount of lines of code. Handy!

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">