[英]Is this a good python design?
I'm using django and i wrote this decorator to take away some of the repetitive code i found for ajax views and i want to know your opinion (too basic, bad design, try this instead, ok, etc). 我使用的是django,我写了这个装饰器,以带走我为ajax视图找到的一些重复代码,我想知道您的意见(过于基本,不良的设计,请改用此方法,可以,等等)。
def ajax_only(func):
def _ajax_only(request,*args,**kwargs):
if not request.is_ajax():
return HttpResponse('<p>Ajax not supported.</p>')
else:
return func(request,*args,**kwargs)
return _ajax_only
The only other tip I'd have here is to suggest the use of the functools.wraps
decorator - it allows the decorated function to keep some attributes (such as function name), which makes it easier for debugging - the code above would be like: 我在这里仅有的其他建议是建议使用
functools.wraps
装饰器-它允许装饰的函数保留一些属性(例如函数名),这使调试更加容易-上面的代码将像:
from functools import wraps
def ajax_only(func):
@wraps(func)
def _ajax_only(request,*args,**kwargs):
if not request.is_ajax():
return HttpResponse('<p>Ajax not supported.</p>')
else:
return func(request,*args,**kwargs)
return _ajax_only
是的,这看起来像是装饰器的典型有效用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.