【问题标题】:applying view decorators to MethodView derived classes将视图装饰器应用于 MethodView 派生类
【发布时间】:2012-12-24 06:27:22
【问题描述】:

在我的烧瓶应用程序中,所有视图都来自 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?

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

【问题讨论】:

    标签: python flask decorator


    【解决方案1】:

    我已经写了基于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>]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-06
      • 2020-03-07
      • 2019-07-23
      • 2023-02-07
      • 2015-02-01
      • 2019-05-02
      • 2016-07-24
      • 2014-10-20
      相关资源
      最近更新 更多