Declaring django views like web.py views

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.http import HttpResponse as response
from django.http import HttpResponseNotAllowed

class ViewClass:
    def __call__(self, request, *args, **kwargs):
        self.request = request
        methods = ['POST', 'GET']
        self.methods = [method for method in dir(self)\
                 if callable(getattr(self, method)) and method in methods]

        if request.method in self.methods:
            view = getattr(self, request.method)
            return view(*args, **kwargs)
        else:
            return HttpResponseNotAllowed(self.methods)

class IndexView(ViewClass):
    def GET(self):
        return response("all ok %s" % self.request.method)

    def POST(self):
        return response("all ok %s" % self.request.method) 

index = IndexView()

More like this

  1. RFC: Shim to allow view classes rather than functions by peterbraden 4 years, 3 months ago
  2. CustomQueryManager by zvoase 4 years, 11 months ago
  3. Upload progress handler using cache framework by ebartels 5 years, 2 months ago
  4. Allow separation of GET and POST implementations by agore 1 year ago
  5. Complex Form Preview by smagala 4 years, 2 months ago

Comments

danigm (on February 5, 2010):

In urls.py the view is "index"

#

pyrou2 (on November 24, 2010):

That's not Thread safe..

If two views are called in the same time.. you'll be exposed to a huge problem :

Having self.request in the first call context matching to the request of the second one.


If you want something great, refer to the new generic class-based views. http://docs.djangoproject.com/en/dev/topics/class-based-views/

from django.views.generic import View

class IndexView(View):

    def get(self, request, *args, **kwargs):
        return self.render_to_response("all ok %s" % request.method)

    def post(self, request, *args, **kwargs):
        return self.render_to_response("all ok %s" % request.method)

index = IndexView.as_view()

#

(Forgotten your password?)