[Django]-Having trouble making a custom django view decorator (with args)

10👍

Your first attempt works just fine, but you probably forgot to call the rate_limit() decorator factory.

In other words, your first error occurs if you do this:

@rate_limit
def myview(request, somearg, *args, **kwargs):

instead of:

@rate_limit(seconds=10)
def myview(request, somearg, *args, **kwargs):

You also really want to use functools.wraps() on decorators used in Django, especially if you want to mix this with other Django decorators such as csrf_exempt:

from functools import wraps

def rate_limit(seconds=10):
    def decorator(view):
        @wraps(view)
        def wrapper(request, *args, **kwargs):
            # Do some stuff
            return view(request, *args, **kwargs)
        return wrapper
    return decorator

This ensures that any attributes set on the to-be-wrapped function are copied over correctly to the wrapper.

Leave a comment