[Tutor] Python decorator

Sean Perry shaleh at speakeasy.net
Fri Sep 1 05:52:34 CEST 2006


János Juhász wrote:
> Hi,
> 
> I have just started to play with TurboGears - it is really nice - and I 
> couldn't understand the decorators used by it.
> I have tried to interpret the http://wiki.python.org/moin/PythonDecorators 
> about decorators, but it is too difficult for me.
> 
> May someone explain decorators in very sortly, what is it for and why ?
> Do I need it anyway ?
> 

A decorator is a function that takes a function and returns a new, 
modified function.

In Django (a similar framework) there are a few places where decorators 
are used.

@login_required
def foo_view(args):
   # a view that must be authenticated
   # more code here

This means that before foo_view() is ran the function login_required is 
run. Which in this case will redirect to a login screen if the user is 
not currently authenticated.

here's the Django code:
def user_passes_test(test_func, login_url=LOGIN_URL):
     """
     Decorator for views that checks that the user passes the given test,
     redirecting to the log-in page if necessary. The test should be a 
callable
     that takes the user object and returns True if the user passes.
     """
     def _dec(view_func):
         def _checklogin(request, *args, **kwargs):
             if test_func(request.user):
                 return view_func(request, *args, **kwargs)
             return HttpResponseRedirect('%s?%s=%s' % (login_url, 
REDIRECT_FIELD_
NAME, quote(request.get_full_path())))
         _checklogin.__doc__ = view_func.__doc__
         _checklogin.__dict__ = view_func.__dict__

         return _checklogin
     return _dec

login_required = user_passes_test(lambda u: u.is_authenticated())




More information about the Tutor mailing list