Skip to content

Instantly share code, notes, and snippets.

@canburak
Created January 8, 2012 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save canburak/1578349 to your computer and use it in GitHub Desktop.
Save canburak/1578349 to your computer and use it in GitHub Desktop.
blog post: Automatically decorating all views of a django project
def process_view(self, request, view_func, view_args, view_kwargs):
if not hasattr(settings, "VIEW_AUTHENTICATORS"): return None
mauths = settings.VIEW_AUTHENTICATORS.keys()
module = view_func.__module__
# Trying to find if any authenticator is defined for this module
module_matches = [mauth for mauth in mauths if module.startswith(mauth)]
# if there is no match, bail out
if not module_matches: return None
# if there is a match...
authenticators = settings.VIEW_AUTHENTICATORS[module_matches[0]]
functions = []
# go on parsing the list
for function_path in authenticators:
try:
dot = function_path.rindex('.')
except ValueError:
msg = '%s isn\'t a function path (error from '
'settings.VIEW_AUTHENTICATORS)' % function_path
raise exceptions.ImproperlyConfigured, msg
f_module, f_name = function_path[:dot], function_path[dot+1:]
try:
mod = import_module(f_module)
except ImportError, e:
msg = 'Error importing module %s '
'from settings.VIEW_AUTHENTICATORS: "%s"' % (f_module, e)
raise exceptions.ImproperlyConfigured, msg
try:
f = getattr(mod, f_name)
except AttributeError:
msg = 'View authenticator %s is not defined in %s' % (f_module,
f_name)
raise exceptions.ImproperlyConfigured, msg
functions.append(f)
def compose(f, g): return lambda *args, **kws: f(g(*args, **kws))
multi_compose = functools.partial(reduce, compose)
all_decorators = multi_compose(functions)
decorated_view = all_decorators(view_func)
return decorated_view(request, *view_args, **view_kwargs)
VIEW_AUTHENTICATORS = {
"module.views.secret": [
"django.contrib.auth.decorators.login_required",
"module.decorators.secret_access_required"],
"module.views.public": [
"django.contrib.auth.decorators.login_required",
"ptms.decorators.public_access_required"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment