writing view decorators in django

what the heck is decorators

decorators are the funniest part of python. decorators allow you to execute your additional code at the entry and exit points of a function or a class with a clear syntax. it is very handy when you need to do locking, logging, tracking, caching etc. with your function.

decorators on air

that is the simplest usage of decorators in python.

def sayWelcome(originalFunction):
 
    def decorated():
         print("welcome, my bloody sexy function")
         originalFunction()
    return decorated
 
@sayWelcome
def myfunction():
    print("hi, i am the one who will be decorated")
 
myfunction()

it’s output will be:

emre@amy:~$ python test.py
welcome, my bloody sexy function
hi, i am the one who will be decorated
emre@amy:~$

you can check out some details in here.

applying it to your django project

if you ever used django auth, you must be aware of bundled decorators in django like @authentication_required, @permission_required.

let’s write a “@limited_access” decorator for django auth. If you don’t wanna deal with user groups/permissions this is for you. This allows you to point views for the users you selected.

from django.http import HttpResponseRedirect
class limited_access(object):
    def __init__(self, user_list):
        self.user_list = user_list
    def __call__(self, view_function):
        def wrapped_function(request, *args, **kwargs):
            if not request.user.username in self.user_list:
                # user is not in access_list, so redirect him/her
                return HttpResponseRedirect("http://noaccess.yoursite.com") 
            else:
                return view_function(request, *args, **kwargs)
        return wrapped_function

use this in views like this;

@limited_access(["emre", "mary",])
def test_view(request):
    return HttpResponse("this view is just for emre and mary.")

any suggestions and comments are wellcome.

2 comments

MetehanFebruary 28th, 2010 at 11:06 am

Birde bunun Türkçe olarak yayınlasanızda bilmeyenlerde öğrense?

Emre YılmazFebruary 28th, 2010 at 12:12 pm

ingilizcemi geliştirmek adına bir süre ingilizce yazmaya karar verdim. Türkçeyi şimdilik ikinci plana attık.

Leave a comment

Your comment