在我的烧瓶应用程序中,所有视图都是从MethodView派生的。
class TestView(MethodView):
def __init__(self):
self.form = TestForm()
@login_required
@campaign_required
def get(self,cid):
.........
并且url规则设置在不同的文件中.....
这篇文章中提到的django是否有类似的东西:
What's the difference between the two methods of decorating class-based views?
我需要用很少的限制装饰这个类......如上所述......
答案 0 :(得分:0)
我写了一个基于this snippet的小例子:
class BaseApi(MethodView):
def _content_type(self, method):
""" decorator example """
def decorator(*args, **kwargs):
best = request.accept_mimetypes.best_match(['text/html', 'application/json'])
if best == 'text/html':
return self._html(*method(*args, **kwargs))
elif best == 'application/json':
return self._json(*method(*args, **kwargs))
else:
abort(400, err='Unknown accept MIME type - "%s"' % best)
return
return decorator
def dispatch_request(self, *args, **kwargs):
method = super(BaseApi, self).dispatch_request
if self.method_decorators is None:
return method(*args, **kwargs)
method_decorators = self.method_decorators.get(request.method.lower(), [])
if getattr(method_decorators, '__call__', False):
method_decorators = [method_decorators]
common_decorators = self.method_decorators.get('*', [])
if getattr(common_decorators, '__call__', False):
common_decorators = [common_decorators]
method_decorators.extend(common_decorators)
for decorator in method_decorators:
method = decorator(self, method)
return method(*args, **kwargs)
method_decorators = {
'*': _content_type, # decorators here are applied to all methods
# 'get': <another decorator only for get method>,
# 'post': [<list of decorator functions that are applied for post requests>]
}