Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Created January 3, 2013 05:10
Show Gist options
  • Save hirokiky/4440994 to your computer and use it in GitHub Desktop.
Save hirokiky/4440994 to your computer and use it in GitHub Desktop.
PredicateProcessView which call method in considering of value returned by `predicate`. The returned value is True, PredicateProcessView calles corresponding method named `receiver`. You can set this `receiver` and `predicate` to `dispatch_config`. Watch PonyView for usage.
from django.views.generic import View
from django.http.response import HttpResponse
class RequestParamPredicate(object):
def __init__(self, val):
k = val
v = None
if '=' in val:
k, v = val.split('=', 1)
k, v = k.strip(), v.strip()
self.k = k
self.v = v
def __call__(self, request, *args, **kwargs):
params = getattr(request, request.method)
actual = params.get(self.k)
if actual is None:
return False
if self.v is not None and actual != self.v:
return False
return True
def secure_predicate():
def _secure_predicate(request, *args, **kwargs):
return request.is_secure()
return _secure_predicate
class PredicateProcessView(View):
dispatch_config = {}
def get(self, request, *args, **kwargs):
self.dispatch_config
for custom_receiver, predicate in self.dispatch_config.items():
if predicate(request, *args, **kwargs):
handler = getattr(self, custom_receiver)
break
else:
handler = getattr(self, 'get_default', self.http_method_not_allowed)
return handler(request, *args, **kwargs)
class PonyView(PredicateProcessView):
dispatch_config = {'get_corn': RequestParamPredicate('corn'),
'get_corn_1': RequestParamPredicate('corn=1'),
'get_secure': secure_predicate(),
}
def get_corn(self, request, *args, **kwargs):
return HttpResponse('pony with some corn')
def get_corn_1(self, request, *args, **kwargs):
return HttpResponse('pony with unicorn')
def get_secure(self, request, *args, **kwargs):
return HttpResponse('pony with protection')
def get_default(self, request, *args, **kwargs):
return HttpResponse('pony')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment