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
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 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.