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
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Why not:
???
#
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.