Login

My approach on class based views

Author:
henning
Posted:
June 1, 2010
Language:
Python
Version:
1.2
Score:
0 (after 2 ratings)

By using new the result of a class instantiation is not an object but the result of a method call. This way classes can be used for views the same way as functions.

 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
class BaseView(object):

    def __new__(cls, request, *args, **kwargs):
        self = object.__new__(cls)
        self.args = args
        self.kwargs = kwargs
        self.request = request
        self.__init__()
        return self.handle_request()

    def __init__(self):
        pass

    def handle_request(self):
        if self.request.method == "POST":
            return self.handle_post(*self.args, **self.kwargs)
        else:
            return self.handle_get(*self.args, **self.kwargs)

    def handle_get(self):
        raise NotImplementedError(self.handle_get)

    def handle_post(self):
        raise NotImplementedError(self.handle_post)


if __name__ == "__main__":
    class TestView(BaseView):

        def handle_post(self, value="foo"):
            return "post called with %r" % value


    class FakeRequest(object):
        method = "POST"
    req = FakeRequest()
    print TestView(req)
    print TestView(req, "bar")

More like this

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

Comments

pakalk (on June 1, 2010):

Why not:

def handle(req):
  def handle_get():
    pass

  def handle_post():
    pass

  if req.method == 'POST':
    handle_post()
  else:
    handle_get()

???

#

henning (on June 1, 2010):

pakalk: Because inheritance does not work with nested functions. View classes can be extended and code can be reused. My example isn't complete - I just wanted to show how it can be done. Like BaseView a class for e.g. a RestfulView could be created.

#

Please login first before commenting.