如何继承一个没有它的装饰器的方法? [英] How to inherit a flask MethodView class without its decorators?

查看:153
本文介绍了如何继承一个没有它的装饰器的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原因是不重写相同的API。我想继承一个已经创建的 MethodView 忽略 login_required <装饰者

 类DoStuffA(MethodView):
decorators = [login_required]
)get get(self):
return jsonify({status:ok})

api.add_url_rule('/ dostufa',view_func = DoStuffA.as_view(dostuffa ),methods = ['GET'])
$ b $ class DoStuffB(DoStuffA):
pass

api.add_url_rule('/ dostuffb',view_func = DoStuffB。 as_view(dostuffb),methods = ['GET'])

/ dostuffb


  1. 是否需要验证? / b>


  2. 我的继承语法是正确的吗? >解决方案 View.decorators 列表仅适用于 View.as_view()方法被调用。如果您不希望在您的子类中应用任何装饰器,只需用空序列覆盖该属性即可:

      class DoStuffB (DoStuffA):
    decorator =()#空元组

    现在 DoStuffB.as_view()将找到空元组而不是继承的 DoStuffA.decorators 列表,并且不应用修饰符。


    For the reason of not rewriting the same API. I want to inherit a get method from an already created MethodView and ignore the login_required decorator.

    class DoStuffA(MethodView):
        decorators = [login_required]
        def get(self):
            return jsonify({"status":"ok"})
    
    api.add_url_rule('/dostufa', view_func=DoStuffA.as_view("dostuffa"), methods=['GET'])
    
    class DoStuffB(DoStuffA):
        pass
    
    api.add_url_rule('/dostuffb', view_func=DoStuffB.as_view("dostuffb"), methods=['GET'])
    

    If I do a GET request to /dostuffb,

    1. Does it need to be authenticated?

    2. Is my inheritance syntax correct?

    解决方案

    The View.decorators list is applied only when the View.as_view() method is called. If you don't want any decorators to be applied in your subclass, just override the attribute with an empty sequence:

    class DoStuffB(DoStuffA):
        decorators = ()  # empty tuple
    

    Now DoStuffB.as_view() will find the empty tuple rather than the inherited DoStuffA.decorators list, and no decorators are applied.

    这篇关于如何继承一个没有它的装饰器的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆