Login

My approach on class based views

Author:
henning
Posted:
June 1, 2010
Language:
Python
Version:
1.2
Tags:
class based views
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. Filter to adjust forloop.counter across pages in a paginated view by egmanoj 6 years ago
  2. Renderer decorator by GaretJax 7 years, 4 months ago
  3. Alternative to Class Based Views by sleepycal 2 years, 6 months ago
  4. YUI Autocomplete by pigletto 7 years, 7 months ago
  5. Class based generic views that automatically check permissions by humphreymurray 4 years, 2 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.