My approach on class based 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
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. Convenient class based views by eallik 2 years, 11 months ago
  2. Using class methods as views by panyam 3 years, 11 months ago
  3. Ordered items in the database - alternative by Leonidas 5 years, 11 months ago
  4. Controller Class for Views by jovialbard 1 month ago
  5. Complex Formsets by smagala 4 years, 4 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.

#

(Forgotten your password?)