1

在我的烧瓶应用程序中,所有视图都来自 MethodView。

class TestView(MethodView):
def __init__(self):
    self.form = TestForm()

@login_required
@campaign_required
def get(self,cid):
     .........

并且 url 规则设置在不同的文件中......

这篇文章中提到的django是否有类似的可能:

装饰基于类的视图的两种方法有什么区别?

我需要用一些限制来装饰班级......如上所述......

4

1 回答 1

0

我写了基于这个片段的小例子:

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>]
}
于 2013-03-06T09:04:22.610 回答