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:
# 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:
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!
Niall O'Higgins is an author, event organizer and software consultant. He wrote the book MongoDB and Python, published by O'Reilly. Events he organizes include We Have Tablets, the #1 Bay Area Tablet Computing Meet-up and PyWebSF. He also offers consulting services for Mobile, Tablet and Cloud Computing.
