Login

Declaring django views like web.py views

Author:
danigm
Posted:
February 5, 2010
Language:
Python
Version:
1.1
Score:
-2 (after 2 ratings)

I work a little with web.py framework and I like a lot the view definition.

For each view you define a class and in that class you can define two method, GET and POST. If the http request is a GET request the GET method will be called and if http request is a POST request the POST method is called.

Then you can define common stuff in another method that could be called inside each method, and you have a class for each view.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 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, 6 months ago

Comments

danigm (on February 5, 2010):

In urls.py the view is "index"

#

Please login first before commenting.