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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With