Login

RestView - class for creating a view that dispatches based on request.method

Author:
simon
Posted:
September 21, 2008
Language:
Python
Version:
1.0
Score:
13 (after 15 ratings)

Sometimes it's useful to dispatch to a different view method based on request.method - e.g. when building RESTful APIs where GET, PUT and DELETE all use different code paths. RestView is an extremely simple class-based generic view which (although it's a stretch to even call it that) which provides a simple mechanism for dividing up view logic based on the HTTP method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Example usage:

    class ArticleView(RestView):
    
        def GET(request, article_id):
            return render_to_response("article.html", {
                'article': get_object_or_404(Article, pk = article_id),
            })

        def POST(request, article_id):
            # Example logic only; should be using django.forms instead
            article = get_object_or_404(Article, pk = article_id)
            article.headline = request.POST['new_headline']
            article.body = request.POST['new_body']
            article.save()
            return HttpResponseRedirect(request.path)

Then in your urls.py:

    from my_views import ArticleView
    
    urlpatterns = patterns('',
        ...
        (r'^article/(\d+)/$', ArticleView()),
        ...
    )

"""

from django.http import HttpResponse
import re

nonalpha_re = re.compile('[^A-Z]')

class RestView(object):
    """
    Subclass this and add GET / POST / etc methods.
    """
    allowed_methods = ('GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS')
    
    def __call__(self, request, *args, **kwargs):
        method = nonalpha_re.sub('', request.method.upper())
        if not method in self.allowed_methods or not hasattr(self, method):
            return self.method_not_allowed(method)
        return getattr(self, method)(request, *args, **kwargs)
    
    def method_not_allowed(self, method):
        response = HttpResponse('Method not allowed: %s' % method)
        response.status_code = 405
        return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

simon (on September 22, 2008):

Hah! I was sure someone else had done this before (it's an obvious approach) but my Google-fu failed me.

#

a.v.khodyrev (on July 24, 2009):

How does one use this with 'reverse'?

#

shemigon (on November 14, 2009):

I solved this problem using url patterns with name parameter

#

aerogelio (on December 9, 2015):

Hi, How I can disable csrf protection using this snipet, I try with csrf_except but no work

#

Please login first before commenting.