开发者

Adding a dispatch decorator

I have the following view function:

def gettingstarted_info(request): 
    """
    First page of gettingstarted after Registration.
    """
    if request.user.is_authenticated():
        if request.user.get_profile().getting_started_boolean: 
             return redirect('/home/')                       
        else:
            user = request.user
    else:
        username = request.session.get('username', False)                                                   
        if not username:
            return redirect('/login')                
        else:
            user = User.objects.get(email=username)  
    # the main part of the view function #

I would like to convert the first part of the view function into an @ decorator, so I could have something like --

@gettingstarted_dispatch
def getting_started_info(request):
    # the main part of the view function

I took a look at the docs on the decorator function but was having a bit of difficulty converting the function so I could use it as an @ decorator. The decorator should filter out unauthorized individuals and return the user varia开发者_开发知识库ble (note this is not the same as request.user). How would I do this? Thank you.


I think this function should do the trick for you. :)

def gettingstarted_dispatch(f):
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated():
            if request.user.get_profile().getting_started_boolean:
                return redirect('/home/')
            else:
                user = request.user
        else:
            username = request.session.get('username', False)
            if not username:
                return redirect('/login')
            else:
                user = User.objects.get(email=username)
        kwargs['user'] = user
        return f(request, *args, **kwargs)
    return wrap

The function passes the user variable as the user keyword arg.

Alternatively, if you prefer, user as the second arg...

            else:
                user = User.objects.get(email=username)
        return f(request, user, *args, **kwargs)
    return wrap

Also, here's a really nice in depth tutorial on how to do decorators. :)

(Part I) http://www.artima.com/weblogs/viewpost.jsp?thread=240808
(Part II) http://www.artima.com/weblogs/viewpost.jsp?thread=240845
(Part III) http://www.artima.com/weblogs/viewpost.jsp?thread=241209

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜