Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Django view decorator not getting the request passed to it?

I have a setup looking something like this:

def foo_decorator(function):
    @wraps(function)
    def decorator(*args, **kwargs):
        print kwargs
        return function(*args, **kwargs)

    return decorator

@foo_decorator
def analytics(request, page_id, promotion_id):
    pass

Outputting:

{'promotion_id': u'11','page_id': u'119766481432558'}

Why is my decorator not getting request passed to it?

like image 551
Kit Sunde Avatar asked Feb 22 '12 15:02

Kit Sunde


People also ask

How do you use decorators in Django?

Decorating class-based viewsTo add a decorator function to every instance of a class-based view, you need to decorate the class definition itself. To do this, you pass the name of the method to be decorated as the keyword argument name: from . decorators import authentication_not_required from django.

Are decorators Pythonic?

Recall that a decorator is just a regular Python function. All the usual tools for easy reusability are available. Let's move the decorator to its own module that can be used in many other functions. Note: You can name your inner function whatever you want, and a generic name like wrapper() is usually okay.

Why decorators are used in Django?

Decorators are a way to restrict access to views based on the request method or control caching behaviour. This is particularly useful when you want to separate logged-in users from unauthenticated users or create an admin page that only privileged users can access.


1 Answers

request isn't a keyword argument to the view, it's the first positional argument. You can access it as args[0].

def foo_decorator(function):
    @wraps(function)
    def decorator(*args, **kwargs):
        print args[0]
        return function(*args, **kwargs)

    return decorator

I would recommend that you change the function signature to include request explicitly:

def foo_decorator(function):
    @wraps(function)
    def decorator(request, *args, **kwargs):
        print request
        return function(request, *args, **kwargs)

    return decorator
like image 167
Alasdair Avatar answered Oct 20 '22 22:10

Alasdair