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!

Share this on a social bookmarking site:
  • Digg
  • del.icio.us
  • Netvouz
  • description
  • ThisNext
  • MisterWong
  • Reddit
  • StumbleUpon

Tags: , , ,

Related posts:
  • Pylons tip #3: Easy caching with Beaker
  • Pylons tip #2: Using SQLite with Pylons
  • Facebook apps in Python and Pylons part 2
  • Facebook apps in Python and Pylons part 1
  • Leave a Reply