制作自定义django视图装饰器(带有args)时遇到问题 [英] Having trouble making a custom django view decorator (with args)
问题描述
因此,我阅读了所有类似的问题,并复制了他们写的内容,但仍然遇到问题。所以我想要这样的东西
So I've read all the similar questions and copied what they wrote but I still keep having issues. So I want something like this
# Yes, I know django has one but I want to make my own
@rate_limit(seconds=10)
myview(request, somearg, *args, **kwargs):
# Return a response
...
def rate_limit(seconds=10):
def decorator(view):
def wrapper(request, *args, **kwargs):
# Do some stuff
return view(request, *args, **kwargs)
return wrapper
return decorator
我收到错误消息
decorator() got an unexpected keyword argument 'somearg'
所以我追加装饰器以接受args和kwargs并得到此错误
So I append decorator to take in args and kwargs and get this error
# New decorator signature
def decorator(view, *args, **kwargs)
和错误
'function' object has no attribute 'status_code'
编辑:
因此,该解决方案得以使用。谢谢 Martijn Pieters !
@rate_limit()
而不是
@rate_limit
推荐答案
您的第一次尝试效果很好,但是您可能忘记了调用 rate_limit()
装饰器工厂。
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):
而不是:
@rate_limit(seconds=10)
def myview(request, somearg, *args, **kwargs):
您还真的想使用 functools.wraps()
在Django中使用的装饰器上,尤其是如果您愿意将此与其他Django装饰器(例如 csrf_exempt
)混合使用:
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
此ens确保将要包装的函数上设置的任何属性正确复制到包装器中。
This ensures that any attributes set on the to-be-wrapped function are copied over correctly to the wrapper.
这篇关于制作自定义django视图装饰器(带有args)时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!