Skip to content

Instantly share code, notes, and snippets.

@Lanny
Created July 29, 2017 23:06
Show Gist options
  • Save Lanny/258723c74485fb01ee85272075bad967 to your computer and use it in GitHub Desktop.
Save Lanny/258723c74485fb01ee85272075bad967 to your computer and use it in GitHub Desktop.
flexible class for splitting handling of different HTTP methods being dispatched to the same view into separate class methods
class MethodSplitView(object):
"""
A flexible class for splitting handling of different HTTP methods being
dispatched to the same view into seperate class methods. Subclasses may
define a separate class method for each HTTP method the view handles (e.g.
GET(self, request, ...), POST(self, request, ...) which will be called with
the usual view signature when that sort of reqeust is made.
Subclasses may also define a `pre_method_check` method which, if it returns
a HttpResponse, will be used to response to the request instead of
delegating to the corrosponding method.
"""
def __call__(self, request, *args, **kwargs):
if getattr(self, 'active_required', False):
if not request.user.is_active:
return HttpResponseForbidden('You must be an active user '
'to do this')
if getattr(self, 'staff_required', False):
if not request.user.is_staff:
return HttpResponseForbidden('You must be staff to do this.')
meth = getattr(self, request.method, None)
if not meth:
return HttpResponseBadRequest('Request method %s not supported'
% request.method)
response_maybe = self.pre_method_check(request, *args, **kwargs)
if isinstance(response_maybe, HttpResponse):
return response_maybe
return meth(request, *args, **kwargs)
def pre_method_check(request, *args, **kwargs):
return None
@classmethod
def as_view(cls):
if getattr(cls, 'require_login', False):
return login_required(cls())
else:
return cls()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment