A Python module that makes it easy RESTful views in Django
Python
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
README.rst
restview.py

README.rst

restview.py

A Python module that makes it easy RESTful views in Django.

RestView

This class is based on this snippet from Simon Willison

In foo.views extend the RestView class:

from restview import RestView, JsonHttpResponse, login_required

class FooRestView(RestView):
    def GET(self, request, id):
        foo = get_object_or_404(Foo, pk=id)
        json = {'property1': foo.property1, 'property2': foo.property2}
        return JsonHttpResponse(json)

    @ajax_required  # Accept requests only from AJAX calls
    @login_required # Authentication
    def POST(self, request, id):
        foo = get_object_or_404(Foo, pk=id)
        foo.property1 = request.POST['property1']
        foo.property2 = request.POST['property2']
        foo.save()
        return HttpResponseRedirect(request.path)

Notice the login_required decorator on def POST(request, id). It requires authentication for POST requests.

RestView by default uses django authentication via Basic Auth, you can override the authenticate function:

class FooRestView(RestView):
    ...
    def authenticate(self, request):
        return request.GET.get('pass') == 'secret'

Finally, on the urls.py:

urlpatterns = patterns('',
    ...
    (r'^foo/(?P<id>\d+)/$', FooRestView),
)

JsonHttpResponse

Usage:

>>> json = {'blogs': [{'name': u'Nuno Mariz Weblog', 'url' : u'http://mariz.org'}]}
>>> return JsonHttpResponse(json)

or

>>> response = JsonHttpResponse()
>>> response.write(json)
>>> return response

XmlHttpResponse

Usage:

>>> xml = '<?xml version="1.0" encoding="utf-8"?>'
>>> xml += '<blogs>'
>>> xml += '<blog><name>Nuno Mariz Weblog</name><url>http://mariz.org</url></blog>'
>>> xml += '</blogs>'
>>> return XmlHttpResponse(xml)