Having trouble making a custom django view decorator (with args)

╄→尐↘猪︶ㄣ 提交于 2019-12-03 20:44:16

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!